开发者

Ruby on Rails: How do I do nested forms with a has_one relationship?

开发者 https://www.devze.com 2023-02-01 17:01 出处:网络
class Po开发者_运维百科llOption < ActiveRecord::Base belongs_to :poll has_one :address end class Address < ActiveRecord::Base
class Po开发者_运维百科llOption < 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

Those are my relevant models. Any ideas? I kinda just need a good example.


For Rails 4

Product Model

has_one                         :nutrition_fact, dependent: :destroy
accepts_nested_attributes_for   :nutrition_fact

Nutrition Fact Model

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

views/products/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 %>


This should answer:

http://archives.ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

The main idea is to declare accepts_nested_attributes_for :address in your PollOption model and to change your form as indicated in the step 2 of the link I provided.

Another useful link: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号