【问题标题】:Rails :through associations getting error, couldn't find associationRails:通过关联获取错误,找不到关联
【发布时间】:2015-08-24 10:33:34
【问题描述】:

我有 3 个模型,

用户、位置、项目

Location 将只有 1 个用户,但 User 有许多项目或位置。和 Items 属于用户或位置。

class Location < ActiveRecord::Base
  belongs_to :user
  has_many items, through: :users
end

class User < ActiveRecord::Base
  has_many :locations
  has_many :items
end

class Item < ActiveRecord::Base
  belongs_to :user
end

但是我收到了这个错误:

Could not find the association :users in model Location

我知道,我可以在 Location 模型中添加 has_many :users,但 location 应该只有 1 个用户。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activerecord


    【解决方案1】:

    应该是这样的:

    class Location < ActiveRecord::Base
      has_one :user
      has_many items, through: :user
    end
    
    class User < ActiveRecord::Base
      belongs_to :location
      has_many :items
    end
    
    class Item < ActiveRecord::Base
      belongs_to :user
    end
    

    为了更有意义,请这样阅读:

    Locationhas_oneuser

    Userbelongs_tolocation

    Userhas_manyitems

    Itembelongs_touser

    Locationhas_manyitems,through: :user

    本质上,您将模型关系委托给另一个模型。 因此,您不必调用location.user.items,只需调用location.items

    【讨论】:

    • 但是如果用户有很多位置呢?我可以拥有belongs_to 和has_many 位置吗?
    • 我想是的,你可以在 User 模型中同时拥有 belongs_to locationhas_many locations。试一试,让我知道!为此,这可能会有所帮助并给您一些想法:stackoverflow.com/questions/4516416/…
    • 我只是去这个错误...ERROR: column users.location_id does not exist LINE 1: SELECT "users".* FROM "users" WHERE "users"."location_id" = $1 ...这是否意味着,我需要在用户表中添加一个location_id?如果是这样,我认为这是错误的关联,因为如果用户有多个位置,那么user 表将如何存储多个location_id?只是想弄清楚这个关联应该如何运作......我想我快到了
    • 是的,没错。将location_id 添加到users 表中。
    • 这意味着这仅允许用户拥有 1 个位置,对吗?如何使用户可以拥有多个位置?还是我想错了?
    【解决方案2】:

    因为你说...

    我知道,我可以在 Location 模型中添加 has_many :users,但 location 应该只有 1 个用户。

    你可以这样做而不是has_many :users

    has_one :user
    

    【讨论】:

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