开发者

How to "accept" nested class object instances by running a custom method before to store those?

I am using Ruby on Rails 3.1.0 and I would like to run a :reject_if method (as described in the official documentation related to the accepts_nested_attributes_for method in the "One-to-many" association section) on class object instances "at all" (that is, to run the :reject_if method not on attributes - as made in the linked documentation - but on records that should be "subsequently" stored in the database). In few words, I would like to reject\filter some nested model\class object instances that should be stored in the database by running a custom method on those instances.

For example, if I have the following:

class User < ActiveRecord::Base
  has_one :article,

  accepts_nested_attributes_for :article
end

I would like to make something like this (the following code does not work):

class User < ActiveRecord::Base
  has_one :article,

  # Note: by using 'article' in the block I (would like to) refer to class
  # object instances
  accepts_nested_attributes_for :article, :reject_if => { |article| article.can_be_create开发者_运维技巧d? }
end

class Article < ActiveRecord::Base
  def can_be_created?
    true if user.has_authorization?
  end
end

Is it possible? If so, how can I make that?


Make a method that returns a boolean, and give the method name as a symbol to :reject_if, eg:

accepts_nested_attributes_for :article, :reject_if => :article_uncreateable?

def article_uncreateable?
  !Article.new(article_attributes).can_be_created?
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜