ruby-on-rails - 有许多通过关联扩展

标签 ruby-on-rails ruby

是否可以通过关联扩展来设置有多个?我有:

class User < ActiveRecord::Base

  has_many :friendships do
    def accepted
      where status: "accepted"
    end
    def rejected
      where status: "rejected"
    end
  end

  has_many :friends, through: :friendships do
    def accepted
      # Something equivalent to the following using association extension:
      # where("friendships.status = 'accepted'")
    end
    def rejected
      # Something equivalent to the following using association extension:
      # where("friendships.status = 'rejected'")
    end
  end

end

如何使用友谊协会扩展设置我的 friend 协会(通过友谊)?

最佳答案

如果您对 where 关系使用 Arel 表达式,则可以取消绑定(bind)这些方法并将它们重新绑定(bind)到 friends 关联:

class User < ActiveRecord::Base
  has_many :friendships do
    def accepted
      where(Friendship.arel_table[:status].eq('accepted'))
    end
    def rejected
      where(Friendship.arel_table[:status].eq('rejected'))
    end
  end

  has_many :friends, through: :friendships do
    def accepted
      proxy_association.owner.friendships.extensions.first.instance_method(:accepted).bind(self).call
    end
    def rejected
      proxy_association.owner.friendships.extensions.first.instance_method(:rejected).bind(self).call
    end
  end
end

使用该代码,将正确生成 SQL,因此该测试通过:

def test_stuff
  tom = User.create! name: "tom"
  fred = Friend.create! name: "fred"
  jerry = Friend.create! name: "jerry"
  Friendship.create! user: tom, friend: fred, status: 'accepted'
  Friendship.create! user: tom, friend: jerry, status: 'rejected'
  tom.reload
  fred.reload
  assert_equal "fred", tom.friends.accepted.first.name
  assert_equal "jerry", tom.friends.rejected.first.name
end

关于ruby-on-rails - 有许多通过关联扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6470057/

相关文章:

ruby-on-rails - Devise 注册后立即在 Controller 中执行某些操作

ruby-on-rails - 如何为(所有)Rails 生成 RDOC?

ruby-on-rails - 使用 sprockets 2.0(可以使用 2.0.0.beta.15)和 Rails 3.1.0.rc5 为 Michael Hartl 的 Rails Tutorial Sample_app 项目获取未定义的方法

ruby-on-rails - Rails 中的 Gemfile 依赖项

javascript - 莫里斯图不接受我的 json 数据,但接受硬编码的示例数据

ruby-on-rails - Rspec 上的 Redirect_to

ruby-on-rails - has_many_polymorphs 是什么意思 "Referential integrity violation"?

ruby - 如何将数组中的散列转换为ruby中的数组

ruby - 将字符串拆分为每个元素具有特定数量字符的数组

ruby - 如何将 fixnum 添加到 ruby​​ 中的字符串?