我有一个模特
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
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
答案 0 :(得分:1)
我认为,您可以覆盖as_json
模型的OpeningTime
方法。这是article on as_json vs to_json。 Quote:“as_json用于创建JSON的结构作为哈希,并将该哈希呈现为JSON字符串留给ActiveSupport :: json.encode。你永远不应该使用to_json创建一个表示,只有消耗表示。“
所以,你会做类似的事情:
class OpeningTime
def as_json(options)
super(:only => [:attributes_you_want], :methods => [:description_markdown])
end
end
<强>更新强>
您是否尝试过在控制器中关注:
类StoreOpeningTimes&lt; ApplicationController中
def index
@store = Store.find(params[:id])
render json: @store.opening_times
end
端
希望,这有帮助。
答案 1 :(得分:1)
我可能会推荐这样的东西:
DAYS_OF_THE_WEEK = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
]
# I might recommend renaming #opening_times_as_json to #hours
def hours
DAYS_OF_THE_WEEK.map { |day| :day.to_sym => hours_for_day(day) }
end
def hours_for_day(day)
"#{opening_times[index_for_day(day)].open} - #{opening_times[index_for_day(day)].close}"
end
def index_for_day(day)
DAYS_OF_THE_WEEK.index(day_of_week_name)
end