简体   繁体   中英

how to use through in rails model with separate foreign keys

I have a rails app with the models below. I would like to be able to refer to profiles directly from tasks. As I see I should use :through somehow, but I can't figure it out. At the moment let's say if I wanna get the first_name in task model I gotta use task.executor.profile.first_name. Instead of that I would like to use task.executor_profile.first_name.

I need it for ransack where you can refer to the associations with include. If there is an easier solution without having to do the :through association, pls let me know.

UPDATE:

Based on @rlarcombe's I tried delegate but unfortunately Ransack doesn't seem to be supporting that solution, but it's working nicely with rails. Can sby tell me how could I use the :through association in this case?

user.rb

has_many :assigned_tasks, class_name: "Task", foreign_key: "assigner_id", dependent: :destroy
has_many :executed_tasks, class_name: "Task", foreign_key: "executor_id", dependent: :destroy
has_one :profile, dependent: :destroy

profile.rb

belongs_to :user

task.rb

belongs_to :assigner, class_name: "User"
belongs_to :executor, class_name: "User"

All you have to do is define a couple of has_one through associations on your Task model.

These association definitions should give you what you want:

app/models/task.rb

class Task < ActiveRecord::Base
  belongs_to :assigner, class_name: "User"
  belongs_to :executor, class_name: "User"

  has_one :assigner_profile, through: :assigner, source: :profile
  has_one :executor_profile, through: :executor, source: :profile
end

app/models/user.rb

class User < ActiveRecord::Base

  has_many :assigned_tasks, class_name: "Task", foreign_key: "assigner_id", dependent: :destroy
  has_many :executed_tasks, class_name: "Task", foreign_key: "executor_id", dependent: :destroy
  has_one :profile, dependent: :destroy

end

app/models/profile.rb

class Profile < ActiveRecord::Base
  belongs_to :user
end

With these in place, you should now be able to call:

task.assigner_profile.first_name

and

task.executor_profile.first_name

These has_one through associations should work correctly with Ransack.

Thanks

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