【问题标题】:Rails belongs_to with conditions on originating tableRails belongs_to 与原始表的条件
【发布时间】:2013-04-04 22:08:36
【问题描述】:

我有一个Transaction 模型,其中from_owner 是多态的,因为事务可能来自其他几个模型。

class Transaction < ActiveRecord::Base
  belongs_to :from_owner, polymorphic: true
end

from_owner_type 是一个特定值时,我正在尝试设置一个特定的belongs_to

belongs_to :from_person,
           conditions: ['from_owner_type = ?', Person.name],
           class_name: Person,
           foreign_key: 'from_owner_id'

我遇到的问题是conditions 似乎是为Person 而不是Transaction。因此,尝试在 Transaction 上调用 from_person 时出现以下 SQL 错误:

ActiveRecord::StatementInvalid: SQLite3::SQLException: 没有这样的列: from_owner_type: SELECT "people".* FROM "people" WHERE "people"."id" = 1 AND (from_owner_type = 'Person') LIMIT 1

如果Transaction from_owner_type 不是Person,我想要Transaction 上的from_person 返回nil,否则返回相关的Person。我可以设置一个自定义的from_person 方法来执行此操作,但我认为这可能是belongs_to。我想在 CanCan 条件下使用它。我正在使用 Rails 3。

【问题讨论】:

  • 您是否只想将其作为访问所有者的单独方法(如果它是Person),而不是这实际上是一个单独的关联?在这种情况下,自定义方法似乎比试图弯曲belongs_to 来做一些与它原本打算不同的事情更好的选择。您是否有不想使用自定义方法的特定原因?
  • 我希望在 CanCan 中定义像 can :read, Transaction, from_person: {profile_id: profile.id} 这样的能力,我认为这需要一种关系,而不仅仅是一种方法。我认为无论如何我都必须以不同的方式进行定义,使用范围和块,所以这个问题可能最好通过“定义实例方法”来回答。
  • 在 CanCan 中设置条件哈希时,您需要使用数据库列 (see the CanCan wiki),所以我怀疑您的方法可能无论如何都行不通。不能只在部分条件中加上对类名的检查吗?

标签: ruby-on-rails ruby-on-rails-3 activerecord cancan belongs-to


【解决方案1】:

从您的 cmets 看来,这样做的目的似乎是能够设置一个 CanCan 规则,允许用户 :read 任何他们拥有的 Transactions,对吗?您应该可以使用以下规则来做到这一点:

can :read, Transaction, from_owner_id: profile.id, from_owner_type: Person.name

这应该意味着您根本不需要为您的Transaction 模型而烦恼。 (我没有对此进行测试,但理论应该是正确的,即使语法不完全存在。例如,我不确定你 profile.id 来自哪里。)

【讨论】:

  • 不,还有另一层间接:from_owner_id 不是Profile,而是Person。所以我需要from_owner: {profile_id: @profile.id}。我需要从Transaction => Person 访问profile_id Person
  • 将它与from_owner_type 条件结合起来是否不起作用? IE。 can :read, Transaction, from_owner_type: Person.name, from_owner: { profile_id: @profile.id }?可能不是,只是猜测,因为我自己没有使用 CanCan 和多态关联:)
猜你喜欢
  • 2014-04-24
  • 1970-01-01
  • 1970-01-01
  • 2015-07-22
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
相关资源
最近更新 更多