Ruby on rails RubyonRails:如何使用has_-one关系创建嵌套表单? class PollOption
这些是我的相关模型。有什么想法吗? 我需要一个很好的例子。这应该可以回答: 主要思想是在PollOption模型中声明Ruby on rails RubyonRails:如何使用has_-one关系创建嵌套表单? class PollOption,ruby-on-rails,Ruby On Rails,这些是我的相关模型。有什么想法吗? 我需要一个很好的例子。这应该可以回答: 主要思想是在PollOption模型中声明接受\u嵌套的\u属性\u:address,并按照我提供的链接的步骤2所示更改表单 另一个有用的链接:Rails 4的 产品模型 class PollOption < ActiveRecord::Base belongs_to :poll has_one :address end class Address < ActiveRecord::Base
接受\u嵌套的\u属性\u:address
,并按照我提供的链接的步骤2所示更改表单
另一个有用的链接:Rails 4的
产品模型
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
营养事实模型
has_one :nutrition_fact, dependent: :destroy
accepts_nested_attributes_for :nutrition_fact
产品控制器
belongs_to :product
视图/产品/new.html.erb
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
另一个有用的链接:博客链接主要针对有很多关系,而不是有一个关系。回答不错,非常有用!漂亮、简单、有用的答案。我一直在寻找如何做到这一点超过2个小时,这击中了要害。
<%= 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 %>