友谊has_many通过模型与多个状态’
目前我的用户模型具有以下代码:
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
但是,当我尝试运行我的黄瓜测试时,我收到此错误:
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)
我认为这意味着它只是试图在内部包含例如pending_friends,具有属性status =“pending”的用户,其中它实际上应该包括属于具有属性status =“pending”的友谊的用户
这是正确的吗? 我该如何解决这个问题?
我找不到任何关于使用has_many
:conditions
文档,但根据生成的错误,我认为指定的条件假定适用于has_many
主题模型,而不是目标模型或它正在引用的模型。
我已更新到以下内容,这有效:
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
但是,如果有人有不同的方法而不必创建accepted_friendshis,requested_friendships和pending_friendships,我很乐意听到它!
status
是friendships
表的列。
因此,当您编写代码时,请提及表名,否则它将采用Current模型的表。
has_many :friends, -> { where "friendships.status = 'accepted'" }, :through => :friendships
- 用户has_many:用户,:通过=>:朋友 – 怎么样?
- has_one:through => multiple
- 在Rails has_many中保存关联记录的顺序:通过关联
- Rails has_many通过表单与连接模型中的复选框和额外字段
- Rails – 按连接表数据排序
- Rails ActiveRecord:Three Table has_many through:associations
- 无法通过关联更新has_many中的连接模型额外属性 – Rails
- 如何查找记录,其has_many通过对象包括某些列表的所有对象?
- HMT collection_singular_ids =删除连接模型是直接的,不会触发销毁回调