Why does Rails not document the ability to use accepts_nested_attributes_for on children -
from rails documentation: "nested attributes allow save attributes on associated records through parent."
i able save attributes on associated records through child. (which great... why not documented or explained?)
(this project can cloned github at: https://github.com/blasto333/vehicles-demo/)
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 |car_form| %> <%= car_form.fields_for :vehicle |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 attributes writer specified association(s).
it means associations: has_many
, has_one
, belongs_to
, habtm
. so... looks pretty documented.
Comments
Post a Comment