Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Foursquare中建立spot和checkin之间的关系_Ruby On Rails_Rails Activerecord - Fatal编程技术网

Ruby on rails 在Foursquare中建立spot和checkin之间的关系

Ruby on rails 在Foursquare中建立spot和checkin之间的关系,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,独家报道如下: 作为一个学习练习,我正在尝试编写一个Rails克隆版,它是Foursquare、Gowalla等众多基于位置的游戏中的一个。我有一些创建和登录商店的用户 在ActiveRecord中: :user has_many :stores :store belongs_to :user 但现在我创建了第三个模型-签入。模型后面的表包含两个字段,user_id用于记录哪个用户签入,store_id用于记录该用户签入的存储 再一次,用AR术语: :checkin belongs_to :u

独家报道如下:

作为一个学习练习,我正在尝试编写一个Rails克隆版,它是Foursquare、Gowalla等众多基于位置的游戏中的一个。我有一些创建和登录商店的用户

在ActiveRecord中:

:user has_many :stores
:store belongs_to :user
但现在我创建了第三个模型-签入。模型后面的表包含两个字段,user_id用于记录哪个用户签入,store_id用于记录该用户签入的存储

再一次,用AR术语:

:checkin belongs_to :user
:checkin belongs_to :store

:user has_many :checkins
:store has_many :checkins
这一切都很好——在我的用户和商店视图中,我可以分别调用@User.checkins和@Store.checkins。唯一的问题是,以这种方式,我只能检索user\u id或store\u id,我真正想要的是用户名或store name。因此,我认为中间签入表非常适合使用:到:

:user has_many :stores, :through => :checkins
:store has_many :users, :through => :checkins

这是有道理的,但问题是一个用户已经有了很多商店——他创建的那些!在他的用户页面上,我需要列出他创建的商店和他签入的商店。我仍在努力改变我的想法,因为我有很多东西,你属于你,所以我不确定这是否会让我走上正确的方向。有人愿意提供线索吗?

Rails可以轻松处理这种情况。一种解决方案:您的用户可以为第二组存储使用不同的关系名称。例如:

class Checkin
  belongs_to :store
  belongs_to :user
end

class Store
  belongs_to :user
  has_many :checkins
end

class User
  has_many :stores
  has_many :checkins

  has_many :visited_stores, :through => :checkins, :source => :store
end
使用:source选项告诉ActiveRecord在构建访问的商店列表时查找Checkin association:store。或者,你可以说

has_many :created_stores, :class_name => "Store"
has_many :stores, :through => :checkins

在这种情况下,您将重命名拥有的商店,而不是访问的商店。

完美!我看到了:source属性,但不完全确定如何使用它。谢谢