views:

16

answers:

1

Another question asked about attributes, but I would like to extend the question to associations.

Say I have a simple blogging model

class Discussion < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :discussion
end

Discussion has a #closed? boolean state. I would like to block all entry points to add more comments to a closed discussion. For example,

discussion.comments << Comment.new
discussion.comments.create(:text => 'Something')

and any others that may exist...

Thanks,

-Jason

A: 

Try adding validation method to Comment model:

class Comment < ActiveRecord::Base
  belongs_to :discussion

  def validate
    errors.add_to_base("Discussion is closed!") if discussion.closed? && new_record?  
  end
end

This validation will prevent from adding new comments to discussion, but will allow editing of existing comments on already closed discussion.

Eimantas