开发者

Confusion over generating custom JSON response in Rails

开发者 https://www.devze.com 2023-04-09 09:05 出处:网络
Model description: User, Widget, Purchase User has_many :purchases has_many :widgets, :through => :purchases

Model description:

User, Widget, Purchase

User
has_many :purchases
has_many :widgets, :through => :purchases

Widget
has_many :purchases
has_many :users, :through => :purchases

Purchase
belongs_to :user
belongs_to :widget

Hope that makes sense and is correct for the below.

Right, in my controller, I have current_user.

I wish to render a nested JSON response for use eventually with jquery templates.

Like this would be ideal:

{
    "purchases": [
        {
            "quantity": 200,
            "price": "1.0",
            "widget": {
                "name": "Fantastic Widget",
                "size": "Large"
            }
        },
        {
            "quantity": 300,
            "price": "3.0",
            "widget": {
                "name": "Awesome Widget",
                "size": "Medium"
            }
        }
    ]
}

This:

render :json => current_user.to_json(:include => [:purchases, :widgets])

Will render some current_user details (not really relevant) and then purchases and widgets at the same level.

This works (outputs some current user details but thats not my main gripe at the moment):

render :json =>  current_user.to_json({:include => :purchases })

But obviously only outputs purchase data. I cannot get a nested include to work (should it work?) even after looking at this sample:

konata.to_json(:inclu开发者_开发知识库de => { :posts => {
                                     :include => { :comments => {
                                                   :only => :body } },
                                     :only => :title } })

From here and this existing stackoverflow question.

So I've just got myself thoroughly confused. Help appreciated.


I would look into utilizing the as_json method in your models to get the desired output. Adding the following to your models should get you going in the right direction.

#users model
def as_json(options={})
   {:purchases => self.purchases}
end

#purchases model
def as_json(options={})
   {:quantity: self.quantity,
   :price: self.price,
   :widget: self.widget}
end

#widgets model
def as_json(options={})
   {:name:self.name,
   :size: self.size}
end

Once you've added these you'd simply user to_json on your user instance and it should output correctly.


RABL lets you craft JSON views similar to the HTML ERB views.

This blog post, "If you’re using to_json, you’re doing it wrong", explains a bit of background and the shortcomings of using to_json.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号