How can I include a model association in a JSON response in Rails?
I've looked at similar posts but can't seem to quite figure it out.
I have the following function which works just fine. The Listing model has a foreign key called price_id which maps to the Price model and its price_range column. Price_id is returned as part of the message object in the JSON response开发者_StackOverflow社区.
How can I return the corresponding price_range value from the association instead of the price_id value (as part of the message obj, and keep the other attributes)?
def update
@listing = Listing.find(params[:listing][:id])
#if params were passed in for updating
if @listing.update_attributes(params[:listing])
#should we return the whole thing or just what's needed?
json_response = {
"success" => @listing.save, #save to DB and assign true/false based on success...
"message" => @listing.attributes #USE attributes to show output the content of the @message obj, and not another object called "message"
}
respond_to do |format|
#json response
format.html { render:json => json_response }
format.xml { render :xml => @listing }
#normal response. Consider leaving this for now?
#format.html { render :action => "detail" } #refresh this page, with new data in it. Consider trying to use redirect instead?
#format.xml { head :ok }
end
end #end if
end
add a method in your Listing model with the price_range and call it in serializable_hash
class Listing
def price_range
price.price_range
end
end
Like explain on comment you can use delegate instead this method :
class Listing
delegate :prince_range, :to => price
end
In you controller you can now do :
json_response = {
"success" => @listing.save, #save to DB and assign true/false based on success...
"message" => @listing.serializable_hash(:methods => [:price_range])
}
Based on what I read in this article, you should be able to do this:
class Listing
def as_json
super(:include => :price)
end
end
Then in your controller:
json_response = {
"success" => @listing.save,
"message" => @listing.as_json
}
If I understand correctly, you want to add @listing.price.price_range
value to the "message" ?
If so, try this:
"message" => @listing.attributes[:price_range] = @listing.price.price_range
精彩评论