Meliborn
Meliborn

Reputation: 6645

Passing parent id in nesting form in Ruby on Rails

Target: save comment for idea model.

Form:

<%= form_for([@idea, IdeaComment.new], :validate => true) do |f| %>
        <div class="control-group">
            <div class="controls">
                <%= f.text_area :text, :placeholder => 'some text', :rows => 5 %>
                <%= validate_errors(IdeaComment.new) %>
            </div>
        </div>
        <%= f.button 'Comment', :class => 'button grad-green', :type => 'submit' %>
    <% end %>

Controller:

 @idea_comment = IdeaComment.new(params[:idea_comment])
 ...

But if we take a look for params hash: enter image description here

How to pass idea_id to "idea_comment"?

Upvotes: 0

Views: 1751

Answers (1)

Substantial
Substantial

Reputation: 6682

Client-side validation is conflicting with resource-oriented forms. Use regular server-side validation instead.

Explanation:

Resource-oriented forms post to a path based on nested resources:

form_for([@idea, IdeaComment.new]) # => POST '/ideas/[:idea_id]/idea_comments'

Rails extracts :idea_id from the request path and passes it in as a parameter. In the create action, the association is set by direct assignment prior to saving:

# controllers/idea_comments_controller.rb
def create
  @idea_comment = IdeaComment.new(params[:idea_comment])
  @idea_comment.idea_id = params[:idea_id]
  # ...
  @idea_comment.save
end

The problem with client-side validation is that it will fail and block form submission until @idea_comment.idea_id is assigned, which doesn't happen until after the form is submitted.

Upvotes: 5

Related Questions