RailsのNested_Attributesは新しい機能なので書籍に記述されていない部分も多い。

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/
によるとモデル側に:reject_ifというオプションを付けるとネストされた子供のparamsが来ても無視する条件を指定できる。便利。

class Member < ActiveRecord::Base
  has_many :posts
  accepts_nested_attributes_for :posts,
  :reject_if => proc { |attributes| attributes['title'].blank? }
end
 
params = { :member => {
    :name => 'joe', :posts_attributes => [
    { :title => 'Kari, the awesome Ruby documentation browser!' },
    { :title => 'The egalitarian assumption of the modern citizen' },
    { :title => '' } # this will be ignored because of the :reject_if proc
  ]
}}
member = Member.create(params['member'])
member.posts.length # => 2
member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
member.posts.second.title # => 'The egalitarian assumption of the modern citizen'  
Ruby on Rails 逆引きクイックリファレンス Rails 2.0対応Ruby on Rails 逆引きクイックリファレンス Rails 2.0対応
著者:大場 寧子
販売元:毎日コミュニケーションズ
発売日:2008-05-31
おすすめ度:4.0
クチコミを見る