wpp
wpp

Reputation: 7313

How to pass multiple values to the create action in Rails?

In my app I have User, Post and Comment models.

When a User wants to comment on Post the new action from the Comments controller takes over. The Post (to be commented on) is shown and the User enters his Comment.

However, when the User submits, I want to pass the Post.id and the Comments.content to the create action. How do I do that?

Here is the comments/new.html.erb

<%= form_for @comment do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.text_area :comment %>
</div>
<div class="actions">
<%= f.submit "Done" %>
</div>
<% end %>

Thanks to all of you. I did the nested routing and my new.html.erb now has

<%= form_for [@post,@comment] do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<% f.hidden_field :post %>
<div class="field">
<%= f.text_area :comment %>
</div>
<div class="actions">
<%= f.submit "Done" %>
</div>
<% end %> 

However I get: undefined method `comment' and I cant figure that bugger out.

Upvotes: 0

Views: 1645

Answers (3)

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

My guess is that each Comment must belong to a Post If that's the case then this seems like the perfect candidate for nested routes. http://guides.rubyonrails.org/routing.html#nested-resources

resources :posts do
  resources :comments
end

So in your case both the post id and the comment id would be part of the URL:

# Will submit to a URL like /posts/1/comments
# or /posts/1/comments/1
<%= form_for [@post,@comment] do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <div class="field">
    <%= f.text_area :comment %>
  </div>
  <div class="actions">
    <%= f.submit "Done" %>
  </div>
<% end %>

You would need to handle the post_id in your comments controller actions.

Upvotes: 1

CHsurfer
CHsurfer

Reputation: 1424

In the view (using HAML)

=form_for( @comment, :as => :comment) do |f|
  =f.hidden_field :post_id
  =f.hidden_field :user_id
  =f.text_area :comment
  =f.submit "Submit"

and in the Comment#new controller:

@comment = Comment.new(:user_id => @user.id, :post_id => @post.id)

Upvotes: 0

Bohdan
Bohdan

Reputation: 8408

First of all you have to pass Post.id to the comments new action. Something like

link_to "Add comment", new_comment_path( params[ :id ] )

I assume that you're following conventions so params[ :id ] is Post.id. Later in your Comment#create instantiate new comment with

@comment = Comment.new( :post_id => params[ :id ] )

which will create comment related to the post. Finally form for new comment

<%= form_for @comment do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <%= f.hidden_field :post_id %>
  <div class="field">
    <%= f.text_area :comment %>
  </div>
  <div class="actions">
    <%= f.submit "Done" %>
  </div>
<% end %>

Upvotes: 0

Related Questions