class PollOption < ActiveRecord::Base
belongs_to :poll
has_one :address
end
class Address < ActiveRecord::Base
belongs_to :user, :poll_options
apply_addresslogic :fields => [[:number, :street], :city, [:state, :zip_code]]
end
这些是我的相关模型。有任何想法吗? 我有点需要一个很好的例子。
答案 0 :(得分:16)
对于Rails 4
产品型号
has_one :nutrition_fact, dependent: :destroy
accepts_nested_attributes_for :nutrition_fact
营养事实模型
belongs_to :product
的ProductsController
def new
@product = Product.new
@product.build_nutrition_fact
end
def edit
@product.build_nutrition_fact if @product.nutrition_fact.nil?
end
private
def product_params
params.require(:product).permit(:title, :price, nutrition_fact_attributes: [:serving_size, :amount_per_serving, :calories])
end
视图/产品/ new.html.erb
<%= form_for @product do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :price %>
<%= f.text_field :price %>
<%= f.fields_for :nutrition_fact do |fact| %>
<%= fact.label :serving_size %>
<%= fact.text_field :serving_size %>
<%= fact.label :amount_per_serving %>
<%= fact.text_field :amount_per_serving %>
<%= fact.label :calories %>
<%= fact.text_field :calories %>
<% end %>
<%= f.submit "Create Product", class: "example-class" %>
<% end %>
答案 1 :(得分:3)
这应该回答:
http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
主要想法是在您的PollOption模型中声明accepts_nested_attributes_for :address
并更改您的表单,如我提供的链接的第2步所示。
另一个有用的链接:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html