Ruby on Rails:如何使用has_one关系进行嵌套表单?

Nul*_*uli 9 ruby-on-rails

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)

  • 漂亮,简单,有用的答案。我一直在寻找如何执行此操作超过2个小时,而这真是令人震惊。 (3认同)
  • 不错的答案,超级有用! (2认同)

apn*_*ing 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