【发布时间】:2013-06-27 22:01:33
【问题描述】:
我正在为以下情况寻找一些最佳实践建议。
我有以下骨架 ActiveRecord 模型:
# user.rb
class User < ActiveRecord::Base
has_many :country_entries, dependent: destroy
end
# country_entry.rb
class CountryEntry < ActiveRecord::Base
belongs_to :user
validates :code, presence: true
end
现在假设我需要为特定用户获取CountryEntry 代码的逗号分隔列表。问题是,我把这个方法放在哪里?有两种选择:
# user.rb
#...
def country_codes
self.country_entries.map(&:code)
end
#...
-或-
# country_entry.rb
#...
def self.codes_for_user(user)
where(user_id: user.id).map(&:code)
end
#...
因此 API 将是:@current_user.country_codes -或- CountryEntry.codes_for_user(@current_user)
似乎将代码放在country_entry.rb 中会更加解耦所有内容,但它会使 API 更难看。关于这个问题的任何一般或个人经验的最佳做法?
【问题讨论】:
标签: ruby-on-rails ruby activerecord sinatra