我正在将一个遗留项目升级到 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
,但在可读性方面会退一步。