在Rails中的belongs_to上有has_one吗?

时间:2009-05-07 18:39:27

标签: ruby-on-rails activerecord associations

我正在构建一个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,对我出错的任何想法?

2 个答案:

答案 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]}}