【问题标题】:Creating a Friendships Model Association in rails在 Rails 中创建友谊模型协会
【发布时间】:2011-12-22 18:14:19
【问题描述】:

问题:@user.friends 不起作用。它返回 2 条记录,应该是 4..

我有以下型号:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, 
    :through => :friendships,
    :conditions => "status = 'accepted'", 
    :order => :fname
  has_many :requested_friends, 
    :through => :friendships, 
    :source => :friend,
    :conditions => "status = 'requested'"
  has_many :pending_friends, 
    :through => :friendships, 
    :source => :friend,
    :conditions => "status = 'pending'"

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"

出于某种原因。 &lt;%=@user.friends%&gt; 不会返回用户的所有朋友。

示例数据:

> @user.friendships.all.length
=> 4
> @user.friendships
=> [#<Friendship id: 20, user_id: 11, friend_id: 20, status: "accepted", created_at: "2011-12-22 12:59:22", updated_at: "2011-12-22 17:02:54">, #<Friendship id: 8, user_id: 11, friend_id: 12, status: "accepted", created_at: "2011-12-22 06:29:02", updated_at: "2011-12-22 07:41:24">, #<Friendship id: 3, user_id: 11, friend_id: 1, status: "approved", created_at: "2011-12-22 05:48:29", updated_at: "2011-12-22 06:22:09">, #<Friendship id: 1, user_id: 11, friend_id: 641, status: "approved", created_at: "2011-12-22 04:47:19", updated_at: "2011-12-22 04:47:19">]
> @user.friends.length
=> 2

@user.friends.length 应该是 4,因为上面的数据显示所有状态为“已接受”。知道我在上面列出的模型关联中哪里搞砸了吗?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord activemodel


    【解决方案1】:

    状态是“批准”两个友谊和“接受”两个。这就是为什么它会根据您的情况只返回两个接受友谊。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 2012-04-05
      • 2013-10-20
      • 1970-01-01
      相关资源
      最近更新 更多