rails - has_many/belongs_to 中的 conditions 的写法
访问量: 2184
在 Rails2/3 中, has_many 可以包含 conditions
在 Rails 4+ 中,需要写成 ->, 例如:
class Payment < ActiveRecord::Base belongs_to :dish_order,-> { where(entity_class: "DishOrder") }, foreign_key: 'entity_id', class_name: 'dish_order' end
注意: -> {... } 这个参数的位置,必须要放到 第二个参数的位置。 (也就是 belongs_to :xx, -> {..}, foreign_key:.... )
-> {} 是一个 scope block, 可以包含: where, includes, readonly , select 。 具体参考: http://guides.rubyonrails.org/association_basics.html