I have figured out how to create a Child form and Include it in the Parent’s program instead of how to exclude the parent_id field. How to assign the parent_id to the child without using the form field?
# routes.rb
resources :parents do
member do
post'create_child'
end
end
and then in your opinion
# parents/show .html.erb
<%= form_for @child, :url => create_child_parent_path(@parent) do |f| %>
...
<% end %>
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
The key here is that even if the form does not contain information about the parent, when you use the build method on the association, the parent_id is assigned by default.
In the show view of the existing Parent, I want to have a form to create Children.
I have figured out how to create A Child form and include it in the Parent’s program instead of how to exclude the parent_id field. How to assign parent_id to the child without using the form field?
I think the best way to deal with this problem is to use the member routing of the parent controller so that when you create a child, you always know what it belongs to through the routing Parent. For example:
# routes.rb
resources :parents do
member do
post'create_child'
end
end
And then in your opinion
# parents/show.html.erb
<%= form_for @child, :url => create_child_parent_path(@parent) do |f| %>
...
<% end %>
Finally in your controller p>
# 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< /pre>The key here is that even if the form does not contain information about the parent, when you use the build method on the association, the parent_id is assigned by default.
< /p>