About validation in rails 4 - ruby-on-rails-4

I got problem in validation with modal popup. This is my index.html.haml:
.container-index
%h1 All Posts Here
%button.btn.btn-info(type="button" data-toggle="modal" data-target="#myModal") New Post
= render 'form'
- #posts.each do |post|
.col-md-4
%h3= link_to post.title,post
%p= post.content
= "#{time_ago_in_words post.created_at} ago "
_form.html.haml:
.container
= simple_form_for current_user.posts.build do |f|
%div.modal.fade#myModal(tabindex="-1" role="dialog" aria-labelledby="myModalLabel")
%div.modal-dialog(role="document")
%div.modal-content
%div.modal-header
%button.close(type="button" data-dismiss="modal" aria-label="Close")
%span(aria-hidden="true") ×
%h3.modal-title#myModalLabel New Post
%div.modal-body
= f.input :title, label:"Title",class:'form-group',name: 'title'
= f.input :content, label:'Content',class:'form-group',name:'content'
%div.modal-footer
%button.btn.btn-danger#mynewpostclose(type="button" data-dismiss="modal") Close
= f.submit 'Create', class:"btn btn-primary"
post.rb:
validates :title, presence: true
validates :content, presence: true
posts_controller.rb:
before_action :find_post, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
#posts = Post.all.order("created_at DESC")
end
def new
#post = current_user.posts.build
end
def create
#post = current_user.posts.build(post_params)
if #post.save
redirect_to #post, notice: 'Created Successfully'
else
render 'new'
end
end
def show
end
def edit
end
def update
if #post.update(post_params)
redirect_to #post, notice: 'Updated Successfully'
else
render 'edit'
end
end
def destroy
#post.destroy
redirect_to posts_path(#post), notice: 'Deleted Successfully'
end
private
def find_post
#post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :content)
end
I do not know how to show up the warningWhen I create a new post without any title or contentit'll link to a blank page and don't create any new postI just wanna call warning inside modal when submit, anyone can help me,plzz?

In your form you need to replace this line
= simple_form_for current_user.posts.build do |f|
with this;
= simple_form_for #post do |f|
This way, when your create action renders the new template, the form will be given the instance of Post which failed to save allowing simple form to display the error messages.

Related

rails 4 semantic ui multi-select show user selections on edit

I am trying to implement multi-select in a form in rails 4, using Semantic UI. I want users to be able to select multiple categories for each post. So far, I am able to display the dropdown select field which pulls all the categories from the database as follows:
<%= form_for #post, :html => {:class => "ui form bk-form group"} do |f| %>
<label>Post title:</label><br />
<%= f.text_field :title, autofocus: true %>
<label>Choose a category:</label><br />
<%= f.select(:category_ids,options_for_select(Category.all.collect{|x| [x.name,x.id,class:'item']}),{prompt:'Select categories'}, multiple: true, class:'ui fluid dropdown selection multiple')%>
<% end %>
With this, I am able to create and save posts and the data is inserted in the database. However, when I try to edit an article, the pre-selected categories do not show. I have tried to set the value: #post.categories option in the select field and still cannot get the existing categories to show. Thanks in advance for your thoughts.
UPDATED
Models are as follows:
class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories
end
class Category < ActiveRecord::Base
has_many :post_categories
has_many :posts, through: :post_categories
end
class PostCategory < ActiveRecord::Base
belongs_to :post
belongs_to :category, :counter_cache => :posts_count
end
Then my posts_controller.rb
class PostsController < ApplicationController
before_action :set_post, only: [:edit, :update, :show]
def index
#posts = Post.all
end
def new
end
def create
#post = Post.new(post_params)
#post.user = current_user
if #post.save
flash[:notice] = "Post was successfully created"
redirect_to user_posts_path
else
flash[:alert] = "Oh Snap!! We could not save your post"
render 'new'
end
end
def edit
end
def update
if #post.update(post_params)
flash[:notice] = "Post was successfully updated"
redirect_to user_posts_path
else
flash[:alert] = "Oh Snap!! We could not update your post"
render 'edit'
end
end
private
def post_params
params.require(:post).permit(:title, :description, :published, :tag_list, category_ids: [])
end
def set_post
#post = Post.find(params[:id])
end
end

Rails - Adding a "Delete" button to a Users Timetable

Hi I have a rails App where Users can have a timetable with a one to many relationship.
When i add this
<%= link_to "delete", user, method: :delete,
data: { confirm: "You sure?" } %>
to _user.html it renders a delete link which deletes a user no problem
but when i add this
<%= link_to "delete", timetable, method: :delete,
data: { confirm: "You sure?" } %>
to _timetable.html.erb it throws an error
ActionController::RoutingError (No route matches [DELETE] "/timetable.4"):
My Routes.rb
get 'password_resets/new'
get 'password_resets/edit'
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'timetable' => 'timetables#new'
get 'signup' => 'users#new'
get 'mobile' => 'users#mobile'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :timetables
resources :users
resources :projects
Timetable Controller
class TimetablesController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def index
#timetables = current_user.timetables.find(current_user)
end
def new
#user = User.find(current_user)
#timetable = Timetable.new
#timetables = #user.timetables.paginate(page: params[:page], per_page: 1)
end
def feed
Timetable.where("user_id = ?", id)
end
def show
#feed_items3 = current_user.feed.paginate(page: params[:page])
#timetable = current_user.timetables.find(params[:id])
end
def create
#timetable = Timetable.new(timetable_params)
#user = User.find(current_user)
if current_user.timetables.create(timetable_params)
flash[:success] = "Timetable created!"
redirect_to timetable_path
else
flash[:success] = "Timetable not created!"
redirect_to timetable_path
end
end
def destroy
#timetable = Timetable.find(params[:id])
#timetable.destroy
redirect_to timetables_path, notice: "The timetable #{#timetable.name} has been deleted."
end
private
def timetable_params
params.require(:timetable).permit(:name, :attachment, :id)
end
def correct_user
#project = current_user.projects.find_by(id: params[:id])
redirect_to root_url if #project.nil?
end
end
Without seeing your Controllers it is hard to be sure, but I would look at a few areas:
Specifying the path & the timetable object to be deleted:
<%= link_to "Delete Timetable", timetable_path(timetable), :method => :delete %>
Ensure that the destroy action for the timetable sits within the timetable_controller
Regarding your routes.rb file I am not sure why you need:
get 'timetable' => 'timetables#new'
and then also
resources :timetables
This is duplication - why not try use 'only' (edit to your preference):
resources :timetables, only: [:index, :new, :create, :destroy]

Rails 4. No route matches, missing required keys: [:id] when submitting form

I have Comment, User and Product models. The user can leave a comment in the Product's show view.
So, I tried to implement the commenting functionality, but when I submit the form with the comment, I get the following error:
ActionController::UrlGenerationError at /comments
No route matches {:action=>"show", :controller=>"products", :id=>nil} missing required
keys: [:id]
The comments table in db looks like this:
id :integer not null, primary key
body :text
created_at :datetime not null
updated_at :datetime not null
user_id :integer
product_id :integer
Here' my views/comments/_form.html.erb:
<%= simple_form_for(#comment) do |f| %>
<%= f.error_notification %>
<%= f.input :body, required: true, placeholder: 'Type in a new comment...', input_html: { class: 'form-control'}, label: false %>
<%= f.button :submit, class: 'btn btn-primary btn-block' %>
<% end %>
My CommentsController.rb:
class CommentsController < ApplicationController
before_action :set_comment, only: [:edit, :update, :destroy]
def create
# #comment = Comment.new(user: current_user, product: params[:id])
#comment = Comment.new(comment_params)
if #comment.save
respond_to do |format|
format.html do
redirect_to product_path(#comment.product_id), notice: 'Comment Created!'
end
end
else
redirect_to product_path(#comment.product_id), notice: 'Something went wrong'
end
end
def edit
end
def update
if #comment.update(comment_params)
respond_to do |format|
format.html do
redirect_to product_path(#comment.product_id), notice: 'Comment Updated'
end
end
else
redirect_to comment_path(#comment_id), notice: 'Something went wrong'
end
end
def destroy
#comment.destroy!
respond_to do
redirect_to product_path(#comment.product_id), notice: 'Comment Deleted'
end
end
private
def set_comment
#comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:body)
end
end
The error is thrown at line 15 in the create method in else condition: redirect_to product_path(#comment.product_id), notice: 'Something went wrong', which means that not only it is giving me the no routes matches error, but it also doesn't save the comment.
In my views/products/show.html.erb there's this line:
<%= render 'comments/form' %>
And in my ProductsController.rb I have this:
def show
#product = Product.find(params[:id])
#comment = Comment.new
#comments = Comment.where(product_id: product.id).order('created_at DESC')
end
In my routes file I have this:
resources :products, only: [:show]
resources :comments, only: [:create, :edit, :update, :destroy]
I've been trying to figure out how to resolve that issue, but didn't succeed. Could you please help me with that?

undefined method `[]' for nil:NilClass railstutorial.org 8.20 >

I'm following the rails-tutorials from Michael Hartl, it's really fun !
but i'm having troubles from upon listing 8.20 and so on.
Cause i guessed i had made a type-o i erased the app and started from scratch again..
The best way to learn is repeat right ?
Well.. also on the second build i got the same error.
> NoMethodError in SessionsController#create
undefined method `[]' for nil:NilClass
Extracted source (around line #7):
6 def create
7 user = User.find_by(email: params[:session][:email].downcase)
8 if user && user.authenticate(params[:session][:password])
9 sign_in user
10 else
after googling for a few hours i tried resetting the db ( drop / create / migrate test:prepare)
i have tried copying pieces of code out of the example (e.g. controllers/helpers/views)
but I cant seem to find the solution.
Here is the code for
session_controller:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
end
end
session helper:
module SessionsHelper
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
self.current_user = user
end
def signed_in?
!current_user.nil?
end
def current_user=(user)
#current_user = user
end
def current_user
remember_token = User.encrypt(cookies[:remember_token])
#current_user ||= User.find_by(remember_token: remember_token)
end
def current_user?(user)
user == current_user
end
def sign_out
current_user.update_attribute(:remember_token,
User.encrypt(User.new_remember_token))
cookies.delete(:remember_token)
self.current_user = nil
end
end
User model
class User < ActiveRecord::Base
before_save {self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX},
uniqueness: {case_sensetive: false}
has_secure_password
validates :password, length: { minimum: 3 }
def User.new_remember_token
SecureRandom.urlsafe_base64
# SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
user controller
class UsersController < ApplicationController
def new
#user = User.new
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
flash.now[:succes] = "Welcome to the sample app"
redirect_to #user
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
end
and the user helper
module UsersHelper
# Returns the Gravatar (http://gravatar.com/) for the given user.
def gravatar_for(user, options = { size: 50 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
how can i properly copy-paste the error log ?
Based on the error you're getting, the problem is clearly somewhere in your Users controller:
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
The error is being generated because params[:session] is, in fact, nil. Now the question is, why?
My guess is that you have a typo in your sign_in form, it should be:
<%= form_for(:session, url: sessions_path) do |f| %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit "Sign in", class: "btn btn-large btn-primary" %>
<% end %>
Please make sure :session is typed correctly.

Rails 4 - NoMethodError undefined method

I got a NoMethodError when i called <%= #post.admin_user.name %>, don't know how to fix it.
Extracted source (around line #4):
<h1><%= #post.title %></h1>
<p><%= #post.body %></p>
<small>Post created at <%= #post.created_at.strftime('%b %d. %Y') %></small><br/><br/>
<%= #post.admin_user.name %>
<p>Category: <%= link_to #post.category.name, category_path(#post.category.id) %></p>
<%= link_to 'Edit Post', edit_post_path %> | <%= link_to 'Go Back', posts_path %> | <%= link_to 'Delete Post', #post, :confirm => "Don't do it man!", :method => :delete %>
</div>
Showing c:/Sites/blog/app/views/posts/show.html.erb where line #5 raised:
undefined method `name' for nil:NilClass
This is my posts_controller.rb
class PostsController < ApplicationController
def index
#post = Post.all
end
def new
#post = Post.new
#category = Category.all
end
def create
#post = Post.new(post_params)
if #post.save
redirect_to posts_path, :notice => 'Your post has been posted!'
else
render 'new'
end
end
def post_params
params.require(:post).permit(:title, :body, :category_id, :admin_user_id, :admin_user, :name)
end
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
if #post.update_attributes(post_params)
redirect_to post_path, :notice => 'Your post has been updated.'
else
render 'new'
end
end
def show
#post = Post.find(params[:id])
#user = AdminUser.all
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to posts_path, :notice => 'Your post has been deleted.'
end
end
This is my post.rb
class Post < ActiveRecord::Base
belongs_to :category
belongs_to :admin_user
end
My admin_user.rd
class AdminUser < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts
end