0

我有一个模型

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
4

2 回答 2

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
于 2013-01-15T19:49:08.710 回答
1

我认为,您可以覆盖模型as_json的方法OpeningTime。这是关于 as_json 与 to_json 的文章。引用:“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 < ApplicationController

 def index
   @store = Store.find(params[:id])
   render json: @store.opening_times
 end

结尾

希望能帮助到你。

于 2013-01-15T14:27:54.913 回答