Validating an association

I have two models, A and B, related to one another by a many to many association and I want to validate an object of model B as it's being added to the association based on both its own attributes and attributes of the particular object of model A that it's being associated with.

I've realized that I can't do this if the association is represented by a habtm relationship since (as far as I can tell - please tell me if I'm wrong) there's no way to refer to the A object in my validation method for B.

Has many :through looks like a better approach here, since I can define the validation method on the join model itself. However this raises a question. I can't create a has many :through association unless the objects on both ends of the association are already saved (right?). But I don't want B to be saved if the association is going to be invalid.

Does this imply that the only way to handle this is to use a transaction to wrap the saving of B and the creation of the association? Or is there a smarter way to do this?

MarkMT wrote:

I have two models, A and B, related to one another by a many to many association and I want to validate an object of model B as it's being added to the association based on both its own attributes and attributes of the particular object of model A that it's being associated with.

I've realized that I can't do this if the association is represented by a habtm relationship since (as far as I can tell - please tell me if I'm wrong) there's no way to refer to the A object in my validation method for B.

You could arrange to get access to the A object using something like:

class A < ActiveRecord::Base    has_and_belongs_to_many bs, :before_add => :set_b_current_a    def set_b_current_a(b) b.current_a = self end end

class B < ActiveRecord::Base    has_and_belongs_to_many as    attr_accessor :current_a end

Thanks, that's pretty interesting.

Mark.