Field for in rails 3 not showing displaying elements inside
I have a model named Order and another model named Member and when I try to display fields from the Members model in my Orders view it doesn't even show when using the fields_for tag. Heres what my code looks like.
order model
class Order < ActiveRecord::Base
has_many :members
end
member model
class Member < ActiveRecord::Base
belongs_to :order
end
orders controller
class OrdersController < ApplicationController
def new
@order = Order.new
3.times { @order.members.build }
@title = "Order Form"
end
def create
@order = Order.new params[:order]
if @order.save
flash[:notice] = "Your order has been created"
redirect_to orders_path
else
@title = "Order Form"
render 'new'
end
end
end
The issue is in my orders view:
<% for member in @order.members %>
This displays 3 times but the information below doesn't
<% fields_for "...", member do |member_form| %>
<p>
Name: <%= member_form.text_field :name %>
</p>
<% end %>
<% end %>
For some odd reason the information in the fields for tag won't even display once. Am I missing something?
If you find out what I am doing wrong, can you please expl开发者_如何学编程ain it to me because I am new to rails.
Thanks in advance!
The block given to a fields_for call on a collection will be repeated for each instance in the collection, essentially creating its own loop, so you don't really need to write your own explicit loop "for member in @order.members". Further, you can leverage nested_attributes functionality to enable saving of associated members directly with @order.save:
class Order < ActiveRecord::Base
has_many :members
accepts_nested_attributes_for :members
end
class Member < ActiveRecord::Base
belongs_to :order
end
In the view:
<%= form_for @order do |order_form| %>
...
<%= order_form.fields_for :members do |member_form| %>
Name: <%= member_form.text_field :name %>
<% end %>
<% end %>
And I think your controller create method should work as you have it.
See the API docs for fields_for, especially the One-to-many subsection.
I think you just need to get rid of the "...",
in your call to fields_for
, as fields for is expecting an object.
Try:
<% fields_for member do |member_form| %>
精彩评论