I have my models & associations currently setup like so:
class User < ActiveRecord::Base
has_and_belongs_to_many :projects
has_many :versions, :through => :projects
end
class Projects < ActiveRecord::Base
has_many :versions
end
class Version < ActiveRecord::Base
belongs_to :project
attr_accessible :user_id, :project_id
before_create :associate_user
def associate_user
# I have no idea what to do here - in fact, I don't think this is even the right place to do this!
end
end
When I do something like user.projects.first.versions.create, I would like the user_id field in Version to be filled with the user_id of the user through whom the model was created. Right now, when I execute that create method, it is set to nil. Now, this makes sense, and I understand why it doesnt work. I just cant figure out how to make this work.
I’ve been scratching my head over this, and cannot figure it out! How would you accomplish this?
UPDATE
Note: although this worked, Levi’s answer below is a much, much better solution, and is what I ended up going with
I figured it out, but I would still like feedback on whether this is the best way to go about this. I feel like there may be a built-in method to rails to do this that I’m missing
Here’s my updated Version model:
class Version < ActiveRecord::Base
belongs_to :production
attr_accessible :user_id, :production_id
after_create :associate_user
def associate_user
@users = User.all(:include => :productions, :conditions => {"productions_users.production_id" => self.production_id})
@users.each do |user|
user.productions.each do |production|
if production.versions.exists?(self)
@version_user = user
end
end
end
self.user_id = @version_user.id
end
end
I would just pass the id in when you create the version.
That way you don’t need the
before_createcallback at all.Edit:
You may also want to consider your database structure. You have a project_id and a user_id on your versions table. You also have the join table (
projects_users) with the same keys. Why not turn that into a real model and add abelongs_to :user_project(or whatever is appropriate) to the Version model? That is one extra join to go from Versions to Projects, but the data model makes more sense.