【发布时间】:2015-07-03 16:39:20
【问题描述】:
我的模型定义如下。我正在尝试使用has_many 做@user.orders。我已经定义了一个方法:orders 来显示我想要的行为。
class Location < ActiveRecord::Base
belongs_to :locationable, polymorphic: true
has_many :orders, ->(location) { where(location.locationable_type == 'User') }, class_name: 'Order', foreign_key: :drop_location_id
# but this does not check for type
# it produces the SQL: SELECT "orders".* FROM "orders" WHERE "orders"."drop_location_id" = $1
end
class Order < ActiveRecord::Base
# location is polymorphic, so type of location can be merchant/user
belongs_to :pickup_location, class_name: 'Location'
belongs_to :drop_location, class_name: 'Location'
end
class User < ActiveRecord::Base
has_many :locations, as: :locationable
# TODO: make it a has_many :orders instead
def orders
Order.where(drop_location: locations)
end
end
使用方法感觉不像 rails 方式。此外,我希望它能够与rails_admin 很好地配合使用。
【问题讨论】:
-
我认为你是对的,使用一种方法没有 Rails 方式。但是,在 has_many 语句中确定范围也是我从未见过或尝试过的事情。我推荐:guides.rubyonrails.org/association_basics.html Rails 中 Active Records 关联的最佳实践设计。
标签: ruby-on-rails activerecord has-many-through