Rails 嵌套属性 (nested attribute) 与 Simple_form

jesktop · 2012年10月11日 · 3425 次阅读

最近一个项目有这样的一个功能,简单的来说就是零件与库存的联系。 零件表保存的是零件的相关信息,库存表保存的就是零件的数量,入库人等等。

其实是个很简单的地方,就是当我们需要入库的时候,也就是新建一个零件(fitting),但是我们需要在填写零件信息的时候,同时填写库存(stock)的相关信息,库存中保存(fitting_id),两者关系为一对一。在这里我使用了accepts_nested_attributes_for

参考:Active Record Nested Attributes

new.slim:

h1 New Fitting
= simple_form_for @fitting do |f|
  = f.input :name
  = f.simple_fields_for :stock_attributes do |d|
    = d.input :amount
  = f.button :submit

这里出现了一个:stock_attributes值,是因为在 model 中使用了accepts_nested_attributes_for。 fitting.rb

class Fitting < ActiveRecord::Base
  has_one :stock, :dependent => :destroy
  accepts_nested_attributes_for :stock
  attr_accessible :name, :stock_attributes
end

accepts_nested_attributes_for 这个类方法,就在该 model 上生成一个属性 writer。 属性 writer 是以该关联命名。例如,为你的 model 增加两个新方法:

author_attributes=(attributes)  pages_attributes=(attributes)

FittingsController 中的 new 与 create 则不需要做任何的特殊变化:

def new
  @fitting = Fitting.new
end

def create
  @fitting = Fitting.new(params[:fitting])
  @fitting.save
  redirect_to fittings_path
end

在点击 submit 时候,传输的数据如下:

{
  "fitting"=>
  {
    "name"=>"XXX",
    "stock_attributes"=>
    {
      "amount"=>"XXX"
    },
    "commit"=>"XX"
  }
}

也就是为什么我们需要使用:stock_attributes值的原因了。

通过这样的方式,就顺利的在创建 fitting 的同时也创建并且关联了 stock。

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号