Including a json object in Rails 3 views

116 views
Skip to first unread message

MikeGBoston

unread,
Mar 22, 2010, 8:49:55 AM3/22/10
to Ruby on Rails: Talk
Hi All,
I'm trying to embed a json object into one of views, and what used to
work in Rails 2.x now no longer works.

I'm generating the json code in my Staff model:
def schedule
appointments = Appointment.find(:all, :conditions => {:staff_id =>
self.id})
appointments.to_json(
:only =>
[:id,:start,:end,:title,:body,:repeat,:repeat_id,:mon_repeat,:tue_repeat,:wed_repeat,:thu_repeat,:fri_repeat,:sat_repeat,:sun_repeat])
end

In my view I'm doing the following:
<script type="text/javascript">
var schedule = <%= h @staff.schedule.to_json %>;
</script>

Finally, the output is not in JSON format, but rather:

<script type="text/javascript">
var schedule = &quot;[{\&quot;title\&quot;:\&quot;available\&quot;,
\&quot;repeat_id\&quot;:null,\&quot;body\&quot;:\&quot;\&quot;,
\&quot;wed_repeat\&quot;:false,\&quot;tue_repeat\&quot;:false,
\&quot;thu_repeat\&quot;:false,\&quot;repeat\&quot;:false,\&quot;id
\&quot;:1,\&quot;end\&quot;:\&quot;2010-03-23T21:30:00Z\&quot;,
\&quot;start\&quot;:\&quot;2010-03-23T21:00:00Z\&quot;,
\&quot;sun_repeat\&quot;:false,\&quot;mon_repeat\&quot;:false,
\&quot;sat_repeat\&quot;:false,\&quot;fri_repeat
\&quot;:false}]&quot;;
</script>

Does anyone know what I can do so that the JSON object is rendered so
that my javascript can read it?

Thanks.

tommy xiao

unread,
Mar 22, 2010, 9:32:29 AM3/22/10
to rubyonra...@googlegroups.com
in rails3 not use h to escape html.

so replaced this code:

<script type="text/javascript">
   var schedule = <%= h @staff.schedule.to_json  %>;
</script>

with below
<script type="text/javascript">
   var schedule = <%= raw @staff.schedule.to_json  %>;
</script>



2010/3/22 MikeGBoston <mgerst...@gmail.com>

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.




--
tommy xiao
E-mail: xiaods(AT)gmail.com
Reply all
Reply to author
Forward
0 new messages