i0n
i0n

Reputation: 926

accessing associations within before_add callback in Rails 3

In Rails 3.2 I have been looking for a way to traverse the associations of an object within the before_add callback.

So basically my use case is:

class User < ActiveRecord::Base
  has_and_belongs_to_many :meetings
end

class Meeting < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_many :comments, :before_add => :set_owner_id
end

class Comment < ActiveRecord::Base
  belongs_to :meeting
end

def set_owner_id(child)
  child.owner_id = <<<THE USER ID for @user >>>
end

and I am creating a comment within the context of a user:

@user.meetings.first.comments.create

How do I traverse the associations from within the before_add callback to discover the id of @user? I want to set this at model level. I have been looking at proxy_association, but I may be missing something. Any ideas?

Upvotes: 2

Views: 796

Answers (1)

johnkoht
johnkoht

Reputation: 602

You should probably create the comment in the context of the meeting, no? Either way, you should handle this in the controller since you'll have no access to @user in your model.

@comment = Meeting.find(id).comments.create(owner_id: @user, ... )

But if you insist on your way, do this:

@comment = @user.meetings.first.comments.create(owner_id: @user.id)

Upvotes: 1

Related Questions