Back

rails - has_many/belongs_to 中的 conditions 的写法

发布时间: 2017-12-11 22:21:00

参考: https://stackoverflow.com/questions/20307874/what-is-the-equivalent-of-the-has-many-conditions-option-in-rails-4

在 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

Back