我有一个模型
class Store
has_many :opening_times
#returns ActiveRecordRelation
我有一个 JSON API,它调用类似的东西
Store.first.opening_times.to_json
有没有办法让这个方法自定义?
当然我知道我可以创建一个像“opening_times_to_json”这样的方法并在我的 json 模板中调用它,但也许有一个很好的 Ruby 或 Rails 方法可以响应不同的格式?
编辑
我想要那样
我现在做到了:
def opening_times_as_json
#opening_times.map{|o| {o.weekday.to_sym=>"#{o.open} - #{o.close}"}}
{ :monday=>"#{opening_times[0].open} - #{opening_times[0].close}",
:tuesday=>"#{opening_times[1].open} - #{opening_times[1].close}",
:wednesday=>"#{opening_times[2].open} - #{opening_times[2].close}",
:thursday=>"#{opening_times[3].open} - #{opening_times[3].close}",
:friday=>"#{opening_times[4].open} - #{opening_times[4].close}",
:satturday=>"#{opening_times[5].open} - #{opening_times[5].close}",
:sunday=>"#{opening_times[6].open} - #{opening_times[6].close}" }
end
这就是我想要的结果:
有没有更优雅的方式来实现这一点?
opening_time model has weekday as string, open as integer and close as integer
EDIT 2 作为请求 opening_time 模型
class Advertisement::OpeningTime < ActiveRecord::Base
attr_accessible :weekday, :open, :close
belongs_to :advertisement
end
和广告
class Advertisement < ActiveRecord::Base
has_many :opening_times
def initialize(*params)super(*params)
if (@new_record)
%w(monday tuesday wednesday thursday firday saturday sunday).each do |weekday|
self.opening_times.build weekday: weekday
end
end
end