Fields_for method in Ruby on Rails
What is the difference between this:
controller
@user = User.new
@order = Order.newview:
<%= form_for :user do |user| %>
...
...
<%= fields_for :order do |order| %>
...
...
<% end %>
<% end %>
I can extract the values in the params-object like this params[:us开发者_如何转开发er] and params[:order]
But I could also have written:
<%= form_for :user do |user| %>
...
...
<%= user.fields_for :order do |order| %>
...
...
<% end %>
<% end %>
and I could have extracted the values in the params-object like this params[:user][:order].
Is the equal, distinguished by the way I extract values from?
Generally you would use the nested version of fields_for
if you were using this line in your User
model:
has_many :orders
accepts_nested_attributes_for :orders
By defining this, you will be able to create a new user and new order record*s* at the same time by using this in the create
action of your UsersController
:
@user = User.new(params[:user])
Because you're using accepts_nested_attributes_for
now, the order attributes will be passed through as params[:user][:orders_attributes]
.
精彩评论