Rails rabl - returning ALL attributes, not just named ones
Asked Answered
L

2

6

Rabl allows you to grab the attributes by naming them in your view, for instance:

object @user
attributes :name, :email

I have a model whose attributes are will not be known, but I'd like to display everything returned from the controller in my instance variable using rabl.

Is there a shortcut like:

attributes :all

etc.

Thanks

Langlois answered 6/12, 2012 at 20:10 Comment(1)
It's been a while since I wrote this, but for future readers github.com/rails/jbuilder is awesome, easy to use, and allows for very quick and easy building of json objects.Langlois
P
21

You should be able to use .column_names:

attributes *User.column_names
Provitamin answered 6/12, 2012 at 20:14 Comment(10)
This is the only answer that I've been able to find.Deliadelian
Hm, I can't seem to call column names on an instance of a user Model. I can call column_names on the User model in the console, but not on a particular instance of the model.Langlois
You're correct, it's a class method - fixed. Alternatively, you can call .class if you can't be sure of the model class: *@user.class.column_namesProvitamin
This works for descendants of ActiveRecord::Base, but what if you are passing a different object into your RABL template, like an OpenStruct?Ulotrichous
For OpenStruct use attributes *@user.instance_variable_get("@table").keys. Any data model should have a way for you to get a list of all data attributes - you just may need to dig a bit to find them. Then apply the solution accordingly.Provitamin
Plus it taught me a bit more about the asterisk operator :)Ephrayim
collection @my_collection attributes *@my_attributes.instance_variable_get("@table").keys But I get the following error: ActionView::Template::Error (undefined method `keys' for nil:NilClass). But the same would work for a single object, not for a collection. How to make it work for a collection ?Find
@Raul: What object is @my_attributes and why do you think it would have a @table instance variable? My recommendation for OpenStruct was assuming you used an OpenStruct object (@user in my case).Provitamin
Sorry, it was a typo error. What I meant was *@my_collection.instance_variable_get("@table").keys. This doesn't work for a collection but works for objects. what could be the workaround for collection then ?Find
@Raul: You should use a partial to change the scope to a single object, and then use the aforementioned approach. Alternatively (and a bit of a hack), you can grab the first item in your collection and check that - this, of course, assumes that you have items in your collection.Provitamin
O
5

If you want to get rid of some columns, like "created_at" and "updated_at":

attributes *User.column_names - ["created_at", "updated_at"]
Overexert answered 15/10, 2013 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.