简体   繁体   中英

Rails: HABTM association between ActiveResource and ActiveRecord class

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:

  1. Is there any other approach to do this ?
  2. Am I missing something in my association methods?

I'd really appreciate any help.

Thanks in advance for help!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM