问题
I have two models: Page has many Sections. I'm not using nested resources because there's a third model also. In my page#show I have a link to create a new Section belonging to the current Page:
<%= link_to 'New Section', new_section_path(:page_id => @page) %>
And in my Section view's form I have:
<%= form_for(@section) do |f| %>
.
.
.
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<%= f.hidden_field :page_id, :value => params["page_id"] %>
<div class="actions">
<%= f.submit %>
</div>
The problem, of course, is that this passes the page_id into the new Section form correctly, but when the user goes back to the form through the edit path, params["page_id"] is empty. I'd like to set the page_id once on create, and never let it be changed again (perhaps there's a way to create a conditional that removes that hidden field from the form, or an even cleaner way?).
Thanks so much for your help.
回答1:
You don't want to get the page_id
from the params, but rather from the resource. You'd do this by assigning the page id to the new resource in the controller.
In your controller:
def new
# In reality you might create the new Section differently,
# but you get the idea.
#
# In other scenarios the page_id might come from the parent
# (in a nested route) or some other source not determined by
# params.
@section = Section.new(page_id: params[:page_id])
end
Then in your template, let the page_id
populate naturally:
<%= f.hidden_field :page_id %>
The edit form will already work, as the record already has a page_id
(as long as all sections have page ids, which I assume they do).
Side note: as a general rule, you want to avoid using request params in views, as this is a mix of concerns (controller <-> view) and will lead to fragility & other issues (as you've found). Rather, let the controller do your resource gathering and assign them to template variables or what have you.
来源:https://stackoverflow.com/questions/19795125/assign-relation-id-to-record-on-create-but-not-on-update