nul*_*ull 21 ruby-on-rails rails-activerecord
我有两个模型加入了has_many:通过关系:
class Publication < ActiveRecord::Base
has_many :publication_contributors
has_many :contributors, :through => :publication_contributors
end
class Contributor < ActiveRecord::Base
has_many :publication_contributors
has_many :publications, :through => :publication_contributors
end
class PublicationContributor < ActiveRecord::Base
belongs_to :publication
belongs_to :contributor
end
Run Code Online (Sandbox Code Playgroud)
(关于我的PublicationContributor模型的一些不寻常和重要的是它不仅仅有一对数据库ID,它还有一个名为contributor_type的字符串属性.这个字符串可能包含诸如"Author"或"Translator"或"Publisher"之类的角色.我不相信这是问题,但解决方案仍然必须考虑到它.)
我想找一个具有特定贡献者的出版物,如下所示:
Publication
.joins(:publication_contributors => :contributor)
.where(:publication_contributors =>
{:contributor_type => "Author",
:contributor => {:name => params[:authors]}})
Run Code Online (Sandbox Code Playgroud)
一切正常,直到我进入嵌套:贡献者,此时SQL溅出:
Mysql2::Error: Unknown column 'publication_contributors.contributor' in 'where clause'
Run Code Online (Sandbox Code Playgroud)
它不是在寻找publication_contributors.contributor_id,而是在寻找不存在的publication_contributors.contributor.我在代码中做错了吗?我找不到像这样具有深层嵌套关联的where子句的任何其他示例.也许它甚至不可能?
更新:
生成的SQL
?[1m?[35mPublication Load (0.0ms)?[0m SELECT `publications`.* FROM `publicati
ons` INNER JOIN `publication_contributors` ON `publication_contributors`.`public
ation_id` = `publications`.`id` INNER JOIN `contributors` ON `contributors`.`id`
= `publication_contributors`.`contributor_id` WHERE `publication_contributors`.
`contributor_type` = 'Author' AND `publication_contributors`.`contributor` = '--
-\n:name:\n- Marilynne Robinson\n' LIMIT 1
Run Code Online (Sandbox Code Playgroud)
另外,我在我的出版物模型中有这个关联:
has_many :authors, :through => :publication_contributors, :source => :contributor, :conditions => {:publication_contributors => {:contributor_type => "Author"}}
Run Code Online (Sandbox Code Playgroud)
我以为我可以这样做:
Publication.joins(:authors).where(:authors => {:name => params[:authors]})
Run Code Online (Sandbox Code Playgroud)
但是这会引发错误:
Mysql2::Error: Unknown column 'authors.name' in 'where clause'
Run Code Online (Sandbox Code Playgroud)
m_x*_*m_x 41
尝试更改你的where子句:
Publication
.joins( :publication_contributors => :contributor )
.where( :publication_contributors => {:contributor_type => "Author"},
:contributors => {:name => params[:authors]} )
Run Code Online (Sandbox Code Playgroud)
ActiveRecord api在这里并不是非常一致:参数where
不能完全正常joins
.这是因为,参数joins
做不反映基础SQL,而论据where
做的.
where
接受一个哈希,其键是表名,值是哈希值(它们本身有列名作为键).它只是在两个表中定位具有相同名称的列时防止歧义.
这也解释了为什么出现第二个问题:关系authors
不存在.
归档时间: |
|
查看次数: |
24674 次 |
最近记录: |