user1427661
user1427661

Reputation: 11794

Passing an Extra Variable From A Form to a Controller

I have a basic setup where from within a Post you can create a Comment. I want to create a POST method that takes a text area and creates a comment with the body from the text area. But my Comment model requires a Post foreign key. Is there any way I can pass the post along with the body without having a hidden form element or something similar? And without using AJAX. Here is my form code:

= form_tag(comments_path) do
  = text_field_tag(:body)
  = submit_tag("Submit Answer")

Upvotes: 1

Views: 90

Answers (2)

crftr
crftr

Reputation: 8546

There's the option of using nested resources. i.e. put it in the URI.

# routes.rb
resources :posts do
  resources :comments
end

This will create a few routes, namely /posts/:post_id/comments(.:format)

A form could look like:

form_for Comment.new, url: post_comments_path(post_id: @post), method: :post do |f|
  # ... 

Though, it will be your controller's responsibility to locate the Post from the params before saving your Comment.


One final note: this approach is justified only because it's a reference to the parent resource. Appending any other loose variables to the URI is lazy.

Upvotes: 2

Anezio Campos
Anezio Campos

Reputation: 1555

In your Post.rb

accepts_nested_attributes_for :comments

In your PostController.rb

def new
  @post = Post.new
  @post.comments.build
end

In your views/posts/new.html.erb

<%= form_for @post do |f| %>
  <%= f.label :content %>
  <%= f.text_field :content %>

  <%= f.fields_for :comments do |comment_form| %>
    <%= comment_form.text_field :body %>
  <% end %>
  <%= f.submit %>
<% end %>

Upvotes: 0

Related Questions