【问题标题】:`.joins` not working for has_many in Rails 3.2 on PostgreSQL`.joins` 不适用于 PostgreSQL 上 Rails 3.2 中的 has_many
【发布时间】:2012-02-01 18:05:14
【问题描述】:

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

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

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?

奇怪的是 enoguh,如果我将关系更改为 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,但它在可读性方面会倒退一大步。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2


    【解决方案1】:

    你应该使用: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)
    

    【讨论】:

      猜你喜欢
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 1970-01-01
      相关资源
      最近更新 更多