开发者

Why does Rails not document the ability to use accepts_nested_attributes_for on children

From the rails documentation: "Nested attributes allow you to save attributes on associated records through the parent."

I am able to save attributes on associated records through the CHILD. (Which is great... but WHY is this not documented or explained?)

(This project can be cloned from github at: https://github.com/blasto333/Vehicles-De开发者_运维百科mo/)

Vehicle Model (Parent)

class Vehicle < ActiveRecord::Base
  has_one :car
  attr_accessible :name, :color, :price, :condition
end

# == Schema Information
#
# Table name: vehicles
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  color      :string(255)
#  price      :string(255)
#  condition  :string(255)
#  created_at :datetime
#  updated_at :datetime
#

Car Model (Child)

class Car < ActiveRecord::Base
  belongs_to :vehicle
  accepts_nested_attributes_for :vehicle
  attr_accessible :doors, :sport, :vehicle_attributes
end


# == Schema Information
#
# Table name: cars
#
#  id         :integer         not null, primary key
#  vehicle_id :integer
#  doors      :integer
#  sport      :boolean
#  created_at :datetime
#  updated_at :datetime
#

Cars Controller

class CarsController < ApplicationController
  def new
    @car = Car.new
    @car.build_vehicle
  end

  def create
    Car.create(params[:car])
  end

end

Cars "new" view

<h1>Cars#new</h1>
<%= form_for @car do |car_form| %>
    <%= car_form.fields_for :vehicle do |vehicle_fields| %>
        <%=vehicle_fields.label :name%>: <%=vehicle_fields.text_field :name%><br />
        <%=vehicle_fields.label :color%>: <%=vehicle_fields.text_field :color%><br />
        <%=vehicle_fields.label :price%>: <%=vehicle_fields.text_field :price%><br />
        <%=vehicle_fields.label :condition%>: <%=vehicle_fields.text_field :condition%><br />
    <% end %>
    <%=car_form.label :doors%>: <%=car_form.text_field :doors%><br />
    <%=car_form.label :sport%>: <%=car_form.text_field :sport%><br />
    <%=car_form.submit%>
<% end %>


http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for

Defines an attributes writer for the specified association(s). 

It means all associations: has_many, has_one, belongs_to, habtm. So... everything looks pretty documented.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜