我已将我的模型定义如下。我正在尝试@user.orders
使用has_many
。我已经定义了一个方法: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
一起使用。
答案 0 :(得分:0)
到目前为止,您应该收到一条错误消息,表明您无法通过多态关联使用has_many。如果你考虑它,它是完全合理的,你的ORM(ActiveRecord)如何形成查询,因为连接将是可怕的。