我正在构建一个rails网站,并且在协会方面遇到了麻烦。基本上我有以下内容:
class Publication < ActiveRecord::Base
belongs_to :category
has_one :site, :through => :category
named_scope :on_site, lambda {|s| {:include => [:site], :conditions => ['sites.slug != ?', 's']}}
end
class Category
belongs_to :site
has_many :publications
end
class Site
has_many :categories
has_many :publications, :through => :categories, :foreign_key => 'category_id'
end
Publication.first.site
生成第一个出版物的网站,site.first.publications
也是如此。
麻烦在于on_site
命名范围,它会产生以下错误,例如Publication.on_site('s')
Mysql::Error: Unknown column 'categories.category_id' in 'on clause': SELECT
`publications`.`id` AS t0_r0, `publications`.`shoot_id` AS t0_r1,
`publications`.`category_id` AS t0_r2, `publications`.`title` AS t0_r3,
`publications`.`slug` AS t0_r4, `publications`.`publish_on` AS t0_r5,
`publications`.`created_at` AS t0_r6, `publications`.`updated_at` AS t0_r7,
`publications`.`description` AS t0_r8, `publications`.`media_base_path` AS t0_r9,
`sites`.`id` AS t1_r0, `sites`.`name` AS t1_r1, `sites`.`created_at` AS t1_r2,
`sites`.`updated_at` AS t1_r3, `sites`.`slug` AS t1_r4, `sites`.`description` AS t1_r5,
`sites`.`dhd_merch_id` AS t1_r6, `sites`.`members_area_url` AS t1_r7 FROM `publications`
LEFT OUTER JOIN `categories` ON (`publications`.`id` = `categories`.`category_id`)
LEFT OUTER JOIN `sites` ON (`sites`.`id` = `categories`.`site_id`) WHERE (sites.slug != 's')
我需要加入到publications.category_id = categories.id,对我出错的任何想法?
答案 0 :(得分:2)
嗯,这是您当前实施的问题:
LEFT OUTER JOIN `categories` ON (`publications`.`id` = `categories`.`category_id`)
该SQL代码段由Site
中的此关联定义创建:
has_many :publications, :through => :categories, :foreign_key => 'category_id'
foreign_key
不正确。 Rails正在categories
中查找名为category_id
的列,并期望该列的值与某个发布ID匹配。但是没有正确的foreign_key
选项可以设置,因为categories
表看起来没有对publications
表的引用 - 它是另一种方式。
我不确定是否可以通过中间has_many :through
关联使ActiveRecord的has_many
关联工作。但我认为你可以使用嵌套关联功能来完成这项工作:
class Publication < ActiveRecord::Base
belongs_to :category
#has_one :site, :through => :category
named_scope :on_site, lambda {|s| {:include => { :category => :site }, :conditions => ['sites.slug != ?', s]}}
end
另一个问题是您在条件数组中将s
放在引号中。它不应该在引号中。
答案 1 :(得分:1)
好吧,如果有兴趣的话,我找到了一个使用范围的:joins
选项的解决方案。我仍然想知道是否可以不使用:joins
。
named_scope :on_site, lambda {|s| {:joins =>
['LEFT OUTER JOIN `categories` ON (`publications`.`category_id` = `categories`.`id`) ',
'LEFT OUTER JOIN `sites` ON (`sites`.`id` = `categories`.`site_id`)'],
:conditions => ['sites.slug = ?', s]}}