【问题标题】:How do I create a scope that traverses a polymorphic association?如何创建一个遍历多态关联的范围?
【发布时间】:2011-10-13 06:41:01
【问题描述】:

我有这些模型(伪代码):

class Order
    has_many :line_items
end

class LineItem
    belongs_to :purchasable, :polymorphic => true
    belongs_to :order
end

class Tile
    has_one :line_item, :as => :purchasable
end

我想制作一个允许我从订单中访问图块的范围。像Order#tiles 这样我就可以在控制器中做这样的事情:

my_order.tiles.new(...)
my_order.tiles.find(params[:id]).update_attributes(...)

如何构建这样的范围? (或者我应该使用其他技术吗?)

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.1 named-scope


    【解决方案1】:

    您的关联无法协同工作。我想你可能正在寻找这样的东西:

    class Order
      has_many :line_items
      has_many :tiles, :through => :line_items, :source => :purchasable, :source_type => "Tile"
      ...
    end
    
    class LineItem
      belongs_to :order
      belongs_to :purchasable, :polymorphic => true
      ...
    end
    
    class Tile
      has_many :line_items, :as => :purchasable
      ...
    end
    

    【讨论】:

    • 我稍微修改了它们以反映我的实际代码。我有几个错误。根据我的修订,您知道如何创建所需的范围吗?
    • 是的,看看我的回答中的has_many :tiles, :through => :line_items, :source => :purchasable, :source_type => "Tile" 行。它会让你做你想做的事。
    • 哦,太好了!没想到这么简单。
    • 这行代码相当简单,但背后的概念更高级。老实说,你不会经常遇到这样的关联,所以你提出了一个非常好的问题。 +1
    猜你喜欢
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2019-12-05
    相关资源
    最近更新 更多