has_many
のオプションがあります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Rails3 | |
class Course < ActiveRecord::Base | |
has_many :students, order: :name, include: [:parents, :brothers], dependent: :destroy | |
end | |
# Rails4 | |
class Course < ActiveRecord::Base | |
has_many :students, ->{ order(:name).includes(:parents, :brothers) }, dependent: :destroy | |
end |
order
と include
が使えなくなってるんですね。しかし、1つのソースでRails3とRails4に対応したい場合どうしようか?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module AssocOpts | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def assoc_opts(options) | |
return [options] if Gem::Version.new(Rails.version) < Gem::Version.new('4.0.0') | |
order_option = options.delete(:order) | |
include_option = options.delete(:include) | |
if order_option && include_option | |
[Proc.new { order(order_option).includes(include_option) }, options] | |
elsif order_option | |
[Proc.new { order(order_option) }, options] | |
elsif include_option | |
[Proc.new { includes(include_option) }, options] | |
else | |
[options] | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Rails3 and Rails4 | |
class Course < ActiveRecord::Base | |
include AssocOpts | |
has_many :students, *assoc_opts(order: :name, include: [:parents, :brothers], dependent: :destroy) | |
end |
あー、conditions どうしようか・・・
返信削除