Sql 友谊有多种状态的贯穿模式';
当前我的用户模型具有以下代码:Sql 友谊有多种状态的贯穿模式';,sql,ruby-on-rails,has-many-through,Sql,Ruby On Rails,Has Many Through,当前我的用户模型具有以下代码: has_many :notifications has_many :friendships has_many :friends, :through => :friendships, :conditions => { status: 'accepted' } has_many :requested_friends, :through => :friendships, :source => :friend, :condition
has_many :notifications
has_many :friendships
has_many :friends, :through => :friendships, :conditions => { status: 'accepted' }
has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => { status: 'requested' }
has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => { status: 'pending' }
我的友谊模式如下:
belongs_to :user
belongs_to :friend, :class_name => "User"
def self.request(user, friend)
unless user == friend or Friendship.exists?(user_id: user, friend_id: friend)
transaction do
Friendship.create(:user => user, :friend => friend, :status => 'pending')
Friendship.create(:user => friend, :friend => user, :status => 'requested')
end
else
return "failed"
end
end
def self.accept(user, friend)
unless user == friend or Friendship.exists?(user_id: user, friend_id: friend)
transaction do
accepted_at = Time.now
accept_one_side(user, friend, accepted_at)
accept_one_side(friend, user, accepted_at)
end
else
return "failed"
end
end
def self.accept_one_side(user, friend, accepted_at)
request = find_by_user_id_and_friend_id(user, friend)
request.status = 'accepted'
request.accepted_at = accepted_at
request.save!
end
但是,当我尝试运行cucumber测试时,出现以下错误:
SQLite3::SQLException: no such column: users.status: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "users"."status" = 'accepted' AND "friendships"."user_id" = ? (ActionView::Template::Error)
我认为,这意味着它试图只包括内部,例如待定的朋友,属性status=“pending”的用户,实际上应该包括属于属性status=“pending”的朋友的用户
是这样吗?我该如何着手解决这个问题
status
是友谊表的一列
因此,在编写代码时,请提及表名,否则它将采用当前模型的表
has_many :friends, -> { where "friendships.status = 'accepted'" }, :through => :friendships
我找不到任何关于使用<代码>:条件<代码>与<代码>有许多<代码>,但根据产生的错误,我推断指定的条件假设适用于<代码>有许多<代码>的模型,不是目标模型或它所参考的模型。我已更新到以下内容,这是有效的:
has_many :notifications
has_many :friendships
has_many :accepted_friendships, :class_name => "Friendship", :conditions => {status: 'accepted'}
has_many :requested_friendships, :class_name => "Friendship", :conditions => {status: 'requested'}
has_many :pending_friendships, :class_name => "Friendship", :conditions => {status: 'pending'}
has_many :friends, :through => :accepted_friendships
has_many :requested_friends, :through => :requested_friendships, :source => :friend
has_many :pending_friends, :through => :pending_friendships, :source => :friend
但是,如果有人有不同的方法,而不必创建已接受的、已请求的和待定的友谊,我很乐意听到 rails 4说“friendships.status='accepted'”不受欢迎,所以我尝试用{:friendships.status='accepted'}替换它,但这不起作用,因为:friendships符号没有.statusmethod@delisdeli,请检查我的最新答案。希望,它会对你有用。