Ruby-on-rails – Create a new child in the Parent program

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 the 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 creating a child, always know the parent to which it belongs through routing. 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

# 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

# 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>

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3324 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.