Tuesday, 15 June 2010

ruby on rails - How to associate the comment form with the correct post -



ruby on rails - How to associate the comment form with the correct post -

i have user/micropost/comment models users can comment on others' microposts. under every post textfield shown users can come in comments struggling find micropost id. assume issue in form_for comments or controllers not sure. love help, thanks.

error: couldn't find micropost without id

models:

user model: has many microposts, has many comments micropost model: belongs user, has many comments comment model: belongs micropost, belongs user

user controller:

def show #(the profile page posts , comments are) @user = user.find(params[:id]) @microposts = @user.microposts.paginate(page: params[:page]) @micropost = current_user.microposts.build if signed_in? @comments = @micropost.comments @comment = current_user.comments.build(:micropost => @micropost) if signed_in? end

comment controller:

def create @micropost = micropost.find(params[:id]) @comment = current_user.comments.build(:micropost => @micropost) #can explain happens in parentheses? @comment.user = current_user @comment.save redirect_to :back end

view/comments/_comment_form:

<%= form_for(@comment) |f| %> <div id="comment_field"> <%= f.text_field :content, placeholder: "say something..." %> </div> <% end %>

routes:

resources :users resources :microposts, only: [:create, :destroy] resources :comments, only: [:create, :destroy]

just add together hidden field micropost_id

<%= form_for(@comment) |f| %> <%= f.hidden_field :micropost_id, value: @micropost.id %> <div id="comment_field"> <%= f.text_field :content, placeholder: "say something..." %> </div> <% end %>

update: passing micropost_id without changes controller

based on comments controller, you're finding micropost based on params[:id] missing when submit form. code below fixes that. however, suggest @ nested resources create controller code prettier , more slick

<%= form_for @comment |f| %> <%= hidden_field_tag :id, @micropost.id %> <div id="comment_field"> <%= f.text_field :content, placeholder: "say something..." %> </div> <% end %>

or update action of form

<%= form_for @comment, url: comments_path(id: @micropost.id) |f| %> <div id="comment_field"> <%= f.text_field :content, placeholder: "say something..." %> </div> <% end %>

update: edits comment controller

# view <%= form_for @comment |f| %> <%= hidden_field_tag :micropost_id, @micropost.id %> <div id="comment_field"> <%= f.text_field :content, placeholder: "say something..." %> </div> <% end %> # comments_controller.rb def create @micropost = micropost.find params[:micropost_id] @comment = current_user.comments.build @comment.micropost = @micropost @comment.save end

ruby-on-rails form-for

No comments:

Post a Comment