1

I have a common set of models extracted into a gem with namespaced models as such:

module Gemifive
  class Activity < ActiveRecord::Base
    belongs_to :user
  end

  class User < ActiveRecord::Base
    has_many :activities
  end
end

That's in the gem "gemifive". So far, so good.

In an app where I use this gem's models, I can do the following: Gemifive::Activity.where(user_id: user.id). This works fine because that table has a user_id column:

SELECT "gemifive_activities".* FROM "gemifive_activities" WHERE "gemifive_activities"."user_id" = 18`

However, the following does not work work: Gemifive::Activity.where(user: user). This generates the following SQL, which is invalid:

SELECT "gemifive_activities".* FROM "gemifive_activities" WHERE "gemifive_activities"."user" = 18

I can access Gemifive::Activity.first.user just fine, so I know the belongs_to association is working. Why can't I use this ActiveRecord convention?

4

1 回答 1

3
Gemifive::Activity.where(user: user)

这是无效的 ARel,简单明了。它与您的模型被命名空间无关。在上面的代码中,ARel 使用了 Hash 的键作为列名,它会被逐字使用。你能做的是

Gemifive::Activity.where(user_id: user)
于 2013-07-08T18:57:16.957 回答