How to output all attributes jbuilder, without having to specify them all? - ruby-on-rails

I'm using json to store document versions of my data in postgresql. I would like to output an entire tree of objects with children, children of children etc and all attributes. If any attributes are added to any of the objects at a later date, I would like them to be include in subsequent json.
Is there any way to output the entire contents without having to least each and every attribute? ie not like this:
json.(object_name, :id, :attr1, :attr2.... etc)

I know this is an old thread, but I was wondering the same thing, and ended up here. Then I found a great answer here => How to extract all attributes with Rails Jbuilder?
#uiureo suggests to use json.merge!, and that worked perfactly for me :)
json.merge! object_name.attributes

If you want your json to ouput like this:
{"id":1,"attribute1":1,"attribute2":2}
You can do this:
json.array! #my_object
However, if you want output that looks likes this:
{"my_object":{"id":1,"attribute1":1,"attribute2":2}}
You can do this:
json.my_object #my_object

You may look at json.except!
json.except! #resource, :id, :updated_at
json.except! #resource
https://github.com/chenqingspring/jbuilder-except

Related

Couchdb finder using CouchRest

I just want to know how can I build a find_all_by_action_and_author_id method in Rails with while using the couchdb. My Model looks like this:
class Activity < CouchRest::Model::Base
property :action, String
property :author_id, String
end
if I try to build a View like that:
design do
view :by_action_and_author_id
end
I dont know how to get the right result, I tried it with this:
Activity.by_action_and_author_id(:keys => [['action','foo'], ['author_id', '1']]).all
But the result is always a empty hash. What is the best way to do this? Any examples?
With PostgreSQL it would look like this
Activity.where(action: 'foo', author_id: '1').all
it cant be so complicated
Thanx
have a look at the generated couchdb-view! you can see which keys get emitted. there is no thing as a mapping there, so i think that [['action','foo'], ['author_id', '1']] should be just ['foo', '1'].
i do not know for sure how couchrest-models handles views, but you can find more infos here: http://www.couchrest.info/model/view_objects.html
have a look at the tag-example.

rails using .send( ) with a serialized column to add element to hash

I'm serializing many attributes on a model Page as hashes.
Because of the high number of attributes, I've taken a meta-programming approach and want to use .send() to iterate through a collection of attributes (such that I don't have to type out an update action for each attribute.
I've done something like this:
insights.each do |ins|
self.send("#{ins.name}=", {(Time.now) => ins.values[1]['value'].to_f})
self.save
end
The problem is that this obviously overwrites the whole serialized column, whereas I wish to add this as an element to the serialized hash.
Tried something like this:
insights.each do |ins|
self.send("#{ins.name}[#{Time.now}]=", ins.values[1]['value'].to_f)
self.save
end
But get a NoMethodError: undefined method page_fan_adds_unique[Mon Aug 13 13:31:58 -0400 2012]=
In the console I'm able to do Page.find(5).page_fan_adds_unique[Time.now]= 12345 and save it as an additional element to the hash as expected.
So how can I use .send() to save an additional element to a serialized hash? Or is there some other approach? Such as using update_attribute or another method? Writing my own? Any help is appreciated, even if the advice is that I shouldn't be using serialization for this.
I'd do :
self.ins.name.send(:[]=, key, value)

Nested to_xml issue?

This may be a basic question but it has been causing me some problems. I am trying to dump an ActiveRecord Object to an XML file using the to_xml function. For whatever reason, this does not work for me if I try to nest it into an element.
Basically I have a hash of ActiveRecord objects that I want to iterate over, and then dump into my XML file like this:
#hash_of_activerecord.each do |key, value|
xml.object do
value.to_xml
end
end
For whatever reason this does not seem to work. What can I do to fix it? Obviously I could just print out each aspect of the object individually but that is not the best solution because I would have to remember to change what is in that loop if I later made a change to the contents of that ActiveRecord object.
Use :include. See http://apidock.com/rails/ActiveRecord/Serialization/to_xml

How to retrieve all attributes from params without using a nested hash?

I am currently in the process of making my first iphone app with a friend of mine. He is coding the front end while I am doing the back end in Rails. The thing is now that he is trying to send necessary attributes to me with a post request but without the use of a nested hash, which means that that all attributes will be directly put in params and not in a "subhash". So more specifically what I want to do is be able to retrieve all these attributes with perhaps some params method. I know that params by default contains other info which for me is not relevant such as params[:controller] etc.. I have named all attributes the same as the model attributes so I think it should be possible to pass them along easily, at least this was possible in php so I kind of hope that Rails has an easy way to do it as well.
So for example instead of using User.new(params[:user]) in the controller I have the user attributes not in the nested hash params[:user] but in params directly, so how can I get all of them at once? and put them inside User.new()?
I found the solution to my problem. I had missed to add the attr_accessible to my model which was what initially returned the error when I tried to run code like: User.new(params) having been passed multiple attributes with the post request.
The solution was very simple, maybe too simple, but since this is my first real application in Rails I feel that it might be helpful for other newbies with similar problems.
If you would like to just pass a more limited version of params to new, you should be able to do something like the following:
params = { item1: 'value1', item2: 'value2', item3: 'value3' }
params.delete(:item2)
params # will now be {:item1=>"value1", :item3=>"value3"}
Also see this for an explanation of using except that you mention in your comment. An example of except is something like:
params.except(:ssn, :controller, :action, :middle_name)
You can fetch the available attributes from a newly created object with attribute_names method. So in this special example:
u = User.create
u.attributes = params.reject { |key,value| !u.attribute_names.include?(key)
u.save

Remove all html tags from attributes in rails

I have a Project model and it has some text attributes, one is summary. I have some projects that have html tags in the summary and I want to convert that to plain text. I have this method that has a regex that will remove all html tags.
def strip_html_comments_on_data
self.attributes.each{|key,value| value.to_s.gsub!(/(<[^>]+>| |\r|\n)/,"")}
end
I also have a before_save filter
before_save :strip_html_comments_on_data
The problem is that the html tags are still there after saving the project. What am I missing?
And, is there a really easy way to have that method called in all the models?
Thanks,
Nicolás Hock Isaza
untested
include ActionView::Helpers::SanitizeHelper
def foo
sanitized_output = sanitize(html_input)
end
where html_input is a string containing HTML tags.
EDIT
You can strip all tags by passing :tags=>[] as an option:
plain_text = sanitize(html_input, :tags=>[])
Although reading the docs I see there is a better method:
plain_text = strip_tags(html_input)
Then make it into a before filter per smotchkiss and you're good to go.
It would be better not to include view helpers in your model. Just use:
HTML::FullSanitizer.new.sanitize(text)
Just use the strip_tags() text helper as mentioned by zetetic
First, the issue here is that Array#each returns the input array regardless of the block contents. A couple people just went over Array#each with me in a question I asked: "Return hash with modified values in Ruby".
Second, Aside from Array#each not really doing what you want it to here, I don't think you should be doing this anyway. Why would you need to run this method over ALL the model's attributes?
Finally, why not keep the HTML input from the users and just use the standard h() helper when outputting it?
# this will output as plain text
<%=h string_with_html %>
This is useful because you can view the database and see the unmodified data exactly as it was entered by the user (if needed). If you really must convert to plain text before saving the value, #zetetic's solution gets you started.
include ActionView::Helpers::SanitizeHelper
class Comment < ActiveRecord::Base
before_save :sanitize_html
protected
def sanitize_html
self.text = sanitize(text)
end
end
Reference Rails' sanitizer directly without using includes.
def text
ActionView::Base.full_sanitizer.sanitize(html).html_safe
end
NOTE: I appended .html_safe to make HTML entities like render correctly. Don't use this if there is a potential for malicious JavaScript injection.
If you want to remove along with html tags, nokogiri can be used
include ActionView::Helpers::SanitizeHelper
def foo
sanitized_output = strip_tags(html_input)
Nokogiri::HTML.fragment(sanitized_output)
end

Resources