INNER JOIN在一个表上使用多个列,rails关联

时间:2017-02-23 15:20:55

标签: mysql ruby-on-rails ruby-on-rails-3 join

我在rails 3.2中有关联,

has_many :skills, :dependent => :destroy,

我想在上述关联中添加一个带有条件的连接,

skills = user.skills.joins('INNER JOIN user_skills ON skills.id = user_skills.skill_id and skills.account_id = user_skills.account_id')

所以不要使用user.skills.joins()。我只想使用user.skills。范围也是一种选择,但可以将其添加到关联中。

我不希望WHERE子句中出现这种附加条件。我希望这是在INNER JOIN中。 (我正在创建该列account_id的索引)

现有查询:

SELECT skills.* FROM skills INNER JOIN user_skills ON skills.id = user_skills.skill_id WHERE skills.account_id = 1 AND skills.account_id = 1 AND user_skills.user_id = 1

预期查询:

SELECT skills.* FROM skills INNER JOIN user_skills ON skills.id = user_skills.skill_id and skills.account_id =user_skills.account_id WHERE skills.account_id = 1 AND user_skills.user_id = 1

协会

skill

has_many :user_skills, :order => :rank
has_many :users, :through => :user_skills, :source => :user, :dependent => :destroy


user_skill

belongs_to :user
belongs_to :skill, :class_name => 'Skill'

user.rb

has_many :user_skills, :order => :rank, :class_name => 'UserSkill' , :foreign_key => "user_id"
has_many :skills, :through => :user_skills, :source => :skill, :dependent => :destroy
accepts_nested_attributes_for :user_skills, :allow_destroy => true

0 个答案:

没有答案