当我直接查询我的数据库时,我得到了预期的结果,但不是在rails中。我猜它与我的关联有关,而且我在3年前曾说过关于Ruby的错误。
Postgres SQL查询:
SELECT users.email, members.software, members.files
FROM users INNER JOIN members
ON members.user_id = users.id
WHERE members.region_id=2
结果:“dan@gmail.com”; t; t“dan@test.com”; t; t
但是来自rails c:
> ←[1m←[36mUser Load (1.0ms)←[0m ←[1mSELECT users.email,
> members.software, members.files FROM "users" INNER JOIN "members" ON
> "members"."user_id" = "users"."id" WHERE "members"."region_id" =
> 2←[0m> => #<ActiveRecord::Relation [#<User id: nil, email: "dan@gmail.com">, #<User id: nil, email: "dan@test.com">]>
该片段是我在我的控制器中尝试创建并硬编码区域ID的结果查询:
User.joins(:members).select("users.email, members.software, members.files").where(members: {region_id: params[:id]})
这些是我的模特:
class User < ActiveRecord::Base
has_many :members
has_many :regions, :through => :members
end
class Region < ActiveRecord::Base
has_many :members
has_many :users, :through => :members
end
class Member < ActiveRecord::Base
belongs_to :user
belongs_to :region
end
这是我将模型或其他东西与我缺失相关联的方式吗?
谢谢!
答案 0 :(得分:2)
你得到的是active_relations
对象。
你可以访问像这样的属性
users = User.joins(:members).select("users.email, members.software as software, members.files as files").where(members: {region_id: params[:id]})
users.each do |u|
p u.email
p u.software
p u.files
end