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
Run Code Online (Sandbox Code Playgroud)
这些是我的相关模型.有任何想法吗?我有点需要一个很好的例子.
drj*_*nco 19
对于Rails 4
产品型号
has_one :nutrition_fact, dependent: :destroy
accepts_nested_attributes_for :nutrition_fact
Run Code Online (Sandbox Code Playgroud)
营养事实模型
belongs_to :product
Run Code Online (Sandbox Code Playgroud)
的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
Run Code Online (Sandbox Code Playgroud)
意见/产品/ 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 %>
Run Code Online (Sandbox Code Playgroud)
这应该回答:
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