Note that there are some explanatory texts on larger screens.

plurals
  1. POAR Method to JSON
    text
    copied!<p>i have a Model</p> <pre><code>class Store has_many :opening_times #returns ActiveRecordRelation </code></pre> <p>i have an JSON API which calls something like </p> <pre><code>Store.first.opening_times.to_json </code></pre> <p>is there a way to make this method custom?</p> <p>of course i know that i can make a method like "opening_times_to_json" and call that in my json template, but maybe there is a nice Ruby or Rails way that a method can response to different formats?</p> <p><strong><em>EDIT</em></strong></p> <p>i want it like that</p> <p>and i did it now : </p> <pre><code>def opening_times_as_json #opening_times.map{|o| {o.weekday.to_sym=&gt;"#{o.open} - #{o.close}"}} { :monday=&gt;"#{opening_times[0].open} - #{opening_times[0].close}", :tuesday=&gt;"#{opening_times[1].open} - #{opening_times[1].close}", :wednesday=&gt;"#{opening_times[2].open} - #{opening_times[2].close}", :thursday=&gt;"#{opening_times[3].open} - #{opening_times[3].close}", :friday=&gt;"#{opening_times[4].open} - #{opening_times[4].close}", :satturday=&gt;"#{opening_times[5].open} - #{opening_times[5].close}", :sunday=&gt;"#{opening_times[6].open} - #{opening_times[6].close}" } end </code></pre> <p>which is the result what i want:</p> <p><img src="https://i.stack.imgur.com/kahtj.jpg" alt="Result"></p> <p>is there a more elegant way to realise that?</p> <pre><code>opening_time model has weekday as string, open as integer and close as integer </code></pre> <h1>EDIT 2 as request opening_time model</h1> <pre><code>class Advertisement::OpeningTime &lt; ActiveRecord::Base attr_accessible :weekday, :open, :close belongs_to :advertisement end </code></pre> <p>and the advertisement</p> <pre><code>class Advertisement &lt; 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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload