Ruby on rails 3 Rails从Friends模型调用用户记录
我建立了一个简单的Ruby on rails 3 Rails从Friends模型调用用户记录,ruby-on-rails-3,model,Ruby On Rails 3,Model,我建立了一个简单的Friend模型,它允许用户拥有多个朋友。下面是它的样子: class Friend < ActiveRecord::Base belongs_to :user class User < ActiveRecord::Base has_many :friends SHOW.HTML.ERB <% if @user.friends.count > 0 %> <% @user.friends.each do |friend| %&g
Friend
模型,它允许用户拥有多个朋友。下面是它的样子:
class Friend < ActiveRecord::Base
belongs_to :user
class User < ActiveRecord::Base
has_many :friends
SHOW.HTML.ERB
<% if @user.friends.count > 0 %>
<% @user.friends.each do |friend| %>
<div class="entry">
<%= friend.username %>
但我不确定在@user.friends循环中我会如何称呼它。任何想法都值得赞赏。如果我需要说得更清楚,请告诉我
更新
我更新了我的用户
模型,如下所示:
has_many :friends, :include => :user
has_many :friended_users, :through => :friends, :source => :user, :uniq => true
但是,当我运行@user.friended_users
时,它会给我用户id
s(与@user相同),而不是朋友id
s
我如何调整该关系,使其链接到朋友id
,而不是用户id
我越想,我想我可能没有在一开始就建立好这段关系。也许一个用户应该有很多:用户,通过=>'friends'
,但这并没有什么意义
更新
我已经根据@twooface的输入更新了我的模型:
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, :through => :friendships
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
class Friend < ActiveRecord::Base
has_many :friendships
has_many :users
class用户:友谊
类友谊'User'
类友元
我只是不确定我的朋友桌应该是什么样子。我假设它应该有一个主键和一个用户id
?如果我创建一个友谊和朋友记录,我可以执行友谊.user
和友谊.friend
并获得正确的结果,但是用户.friends
给了我一个空哈希…我认为你建立的关系有点错误。试着这样做:
class User < ActiveRecord::Base
has_many :friends
has_many :friendships
has_many :friends, :through => :friendships
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
# This class has :user_id and :friend_id
将返回此用户的好友所属的用户数组
希望这有帮助。好的。如果我错了,请纠正我,因为Friend类有:user\u id和:Friend\u id,Friend类也有:user\u id和:Friend\u id?@twoface,我已经根据您所说的更新了我的模型,但我不确定朋友应该是什么样子(请参阅上面的更新)。如果有任何建议,我将不胜感激;谢谢没有Friend类(某种程度上,它是User类的一个实例),所以您只有User类的对象和它们之间的友谊对象。
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, :through => :friendships
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
class Friend < ActiveRecord::Base
has_many :friendships
has_many :users
class User < ActiveRecord::Base
has_many :friends
has_many :friendships
has_many :friends, :through => :friendships
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
# This class has :user_id and :friend_id
User.first.friends