Create a new child at the parent show

In presenting an existing parent view, I would like to have a form for creating Children.

I figured out how to create a child form and include it in the parent show, but not how to exclude the parent_id field. How can I assign parent_id to a child without using a form field?

+3
source share
1 answer

I think the best way to handle this is to use member routes for the parent controller so that when you create the child you always know which parent it belongs to through routing. For instance:

# routes.rb
resources :parents do
  member do
    post 'create_child'
  end
end

And then in your view

# parents/show.html.erb
<%= form_for @child, :url => create_child_parent_path(@parent) do |f| %>
...
<% end %>

And finally, in your controller

# parents_controller.rb
def create_child
  @parent = Parent.find(params[:id])
  @child = @parent.children.build(params[:child])
  if @child.save
    @child = Child.new
  end
  render :action => :show
end

, , parent_id .

+6

Source: https://habr.com/ru/post/1794941/


All Articles