How to return an object from two tables form a rails web serivce?
I have two ActiveRecord models: Event and Place. Event has a property name place_id which points to Place. Place has a column named place_name.
How do I write a web service that returns a json of events with each event also holds the associated place_name value.
I tried开发者_如何学运维 simply adding an attr_accessor field name place_name to the Event model and populate it manually after selecting the events. But when I do: render :json => events_collection_result
the place_name doesn't appear in the json.
All of this logic falls under ActiveRecord Associations. It's a very fundamental piece of Rails functionality, so it's very well documented. That guide should more than suffice.
You'll want to invoke belongs_to :place
if your Event
class definition. From there, you can access an Event's place name via @event.place.place_name
, although I'd recommend you rename place_name
to just name
.
JSON won't display the association by default. There are plenty of ways to remedy this, the most basic of which is to overwrite Event#to_json
, which is the method that is called by default when Rails attempts to produce a JSON representation of an ActiveRecord instance.
精彩评论