2

我正在将一个遗留项目升级到 Rails 3.2.1,但我在使用新的 ActiveRecord 查询界面时遇到了问题,特别是在使用新join方法时。

我有一个模型User,它拥有许多Podcast

class User < ActiveRecord::Base
  has_many :podcasts
end

class Podcast < ActiveRecord::Base
  belongs_to :user
end

我的问题是只有从侧面join调用时才有效。belongs_to

irb(main):005:0> Podcast.joins :user
  Podcast Load (1.4ms)  SELECT "podcasts".* FROM "podcasts" INNER JOIN "users" ON "users"."id" = "podcasts"."user_id"
  => []

irb(main):006:0> User.joins :podcast
  ActiveRecord::ConfigurationError: Association named 'podcast' was not found; perhaps you misspelled it?

奇怪的是,如果我将关系更改为 a ,这一切都有效has_one

我的相关部分schema.rb

create_table "podcasts", :force => true do |t| 
  t.string   "name",         :default => "",   :null => false
  t.string   "url",          :default => "",   :null => false
  t.text     "description"
  t.datetime "last_updated"
  t.boolean  "active",       :default => true
  t.integer  "user_id"
end 

底层数据库是PostgreSQL 9.1.2,而 ruby​​ 是1.8.7-p357

这是预期的行为吗?

我知道我可以将 SQL 传递给join,但在可读性方面会退一步。

4

1 回答 1

4

你应该使用:podcasts

User.joins :podcasts

您使用joins的符号应与您在关联中使用的符号相匹配。来自Active Record Query Interface Guide

class Category < ActiveRecord::Base
  has_many :posts
end
class Post < ActiveRecord::Base
  belongs_to :category
  has_many :comments
  has_many :tags
end

[...]

加入单一协会

Category.joins(:posts)
于 2012-02-01T19:35:40.413 回答