has_one :through => multiple

走远了吗. 提交于 2019-12-10 18:17:26

问题


Both Attendment & Vouching:

belongs_to :event
belongs_to :account

Therefore: 1 to 1 relationship between attendments and vouchings.

Is there a way to do this without my thinking too much?

# attendment
has_one :vouching :through => [:event, :account]

Note: I don't mind thinking too much, actually.


回答1:


Yeah i don't think you can use a has_one for this. Assuming I'm reading this correctly, you have two models:

Attendment Vouching

They both store an event_id and account_id. You want to know from the attendment model, what vouching shares the same event and account as the attendment. I think the easiest solution for this is to write a method inside your attendment.rb file.

class Attendment < ActiveRecord::Base
  # belong to statements go here
  def voucher
    Voucher.where(:event_id => self.event_id, :account_id => self.account_id).first
  end
end


来源:https://stackoverflow.com/questions/6976852/has-one-through-multiple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!