Reputation: 23
I am trying to implement my own methods for habtm association between ActiveResource and ActiveRecord classes in my Rails app.
Here is my classes:
class Project < ActiveResource::Base
end
class Target < ActiveRecord::Base
has_and_belongs_to_many :projects
def project_ids
project_ids
end
def project_ids=(pids)
project_ids = pids
end
def projects
projects = []
pids = project_ids.split(",")
pids.each do |pid|
projects.push(Project.find(pid))
end
end
def projects=(projs)
pids = projs.collect(&:id)
project_ids = pids.join(",")
end
end
I also have join table projects_targets with two columns project_id and target_id.
This does not record the association value into the join table upon creation.
My Questions:
I'd really appreciate any help.
Thanks in advance for help!
Upvotes: 1
Views: 513
Reputation: 185
My advice is to not fight the framework and use the built in methods. If you wanted to implement custom accessors, then you should switch to a has many through because it will give you a model ( of the join table ) that you can work with to set the association manually.
Start here: http://edgeguides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
You will not need the custom accessors project_ids or projects because rails will do the work magically.
You can easily do assignments like so:
some_target.projects << some_project
You don't even have to call some_target.save because the << operator is saving the association and writing the id's to the join table for you.
If you have an array of projects, or an active record relation ( like the result of a where clause) you can pass it in the same way
some_target.projects << array_of_projects
To remove the association, you can call destroy with an object like
some_target.projects.destroy a_specific_project
This won't destroy a_specific_project, but it will un-associate it.
Upvotes: 1