How to customize json output from controller in rails - ruby-on-rails

I have a controller that returns a list of categories and a count of items in each category
Category.joins(:item).group([:category_id,:name]).count
I would like to clean up the json formatting from this
(which is category_id, :name, :count )
{"[10, \"Fruit.\"]":2,"[11, \"Vegetables.\"]":1,"[2, \"Pasty.\"]":1}
to this
{"categoryitemcount":[ {"id":10,"name":"Fruit","count":7}]}
so a custom root name along with named columns
thanks in advance!

The solution to this is demoed in Railscast #219. Basically create a model not backed by a database and which represents the data you want to send back. In my case CategoryItemCount.rb (id, name, count). I built an array of these on the fly using the query given above, and output as json.

Related

Active record where query for value inside of an array

Question: Is it possible to build a class method scope that can query objects based on values inside an array in a table? If yes, how can I do this?
In my example, I have a “wells” table that has an array field called “well_tags”. I want to build a query that returns all objects that have a specified value (such as “ceramic”) in the wells_tags array. The basic query would be something like this:
#well = Well.all
#query = #well.where(“well_tags contains ceramic”)
And then the class method scope would look something like this, with the “well_tag_search” param passed in from the controller:
class Well < ActiveRecord::Base
def self.well_tag_filter(well_tag_search)
if well_tag_search.present?
where(“well_tags contains ceramic")
else
Well.all
end
end
I found another post that asks a similar question (see link below), but I cannot get the answer to work for me...the result is always 'nil' when I know there should be at least 1 object. I am a beginner using sqlite (for now) as my database and rails 4.0.
Active Record Query where value in array field
Thanks!
UPDATE: some progress
I figured out how to create an array of all the objects I want using the ‘select’ method. But I still need to return the results as an Active Record object so I create a class method scope.
#well = Well.select
{ |well| if well.well_tags.present?
then well.well_tags.include? ‘ceramic' end }
#well.class #=> array
Not sure where Show is coming from.
Can you try doing Well.all instead of Show.all?

how to retrieve an aray of only specific attributes in rails 2.3

I have a scenario where I need to retrieve an array of specific attributes from a table. I have a TransportAttendanceBlock table. In the table I have blocked(boolean) and blocked_date attributes. From a controller I am fetching this table by passing params of date and boolean value.
Controller code:
#blocked_date = TransportAttendanceBlock.by_blocked_date_and_blocked(#today,1)
Model
named_scope :by_blocked_date_and_blocked, lambda{|date,status| {:conditions=> {:blocked_date=>date.beginning_of_month..date.end_of_month, :blocked=>status}}}
Here in the controller I am getting the entire objects of TransportAttendanceBlock table.
But I need to just pass any array of dates only in the #blocked_date variable as json.
So how do I extract only blocked_date attributes and assign it to #blocked_date variable. Please help. I am using rails2.3 and ruby 1.8.7
Try this:
#blocked_date = TransportAttendanceBlock.by_blocked_date_and_blocked(#today,1).map(&:blocked_date)

Modifying collection of object string attributes using regex

I have a collection of Item objects. Each item has a description. I want to iterate through the collection, and for each description attribute, I want to replace the word "deliver" to "send". The word "deliver" appears in each description. For ex:
item 1: We will deliver within 3 days.
item 2: We will deliver within 2 days.
item 3: We will deliver within 7 days.
...
For a simple search and replace, it sounds like you want something like this:
collection.each { |item| item.description.gsub!('deliver', 'send') }
If these are ActiveRecord objects or some such, you may also need an item.save in there.
If you need more powerful pattern matching,String#sub and related methods can accept a regex instead of a string for the first argument, but it's probably faster and more readable to use a string if that's all you need. For more details and other options, see the API docs for String#sub.

Persisting string array in single column

Our main domain object has multiple string[] properties (various configuration options) and we are thinking of an elegant way to persist the data. GORM creates joined table for the each array so we end up with about dozen joined tables.
I wonder if it would be possible to serialize each array into single column of the main table (someway delimited) and parse it back into array onload?
Do you have suggestions how to do this? I'm thinking either hibernate usertype or grails property editor? I spent some time with usertypes but without luck.
thanks
pk
you could put the parameters into a map / array, then store them in a db field as Json:
def someDomainInstance = new SomeDomain()
def paramMap = [name:'John', age:24]
someDomainInstance.paramJson = paramMap as JSON
someDomainInstance.save()
Then you can easily convert this string back to a map / array when you interrogate the DB:
def paramMapFromDB = JSON.parse(someDomainInstance.paramJson)
assertEquals 24, paramMapFromDB.age
Something like that, I haven't tested the syntax, but that's the general idea.

Saving a symfony checkbox list

If you create a checkbox list in symfony 1.2 you get an array with the checked options back in the form. If you save the form, your database now contains the words "Array". Is there a way around this? Or should I just json_encode / json_decode the array as ncecessary and save it manually? Seems awfully tedious.
Thanks for reading.
You can use serialize() and unserialize() functions when saving and getting data.
I don't know which orm using but i can explain with propel way.
For example you have post table and Post class. And post table has options column with text or varchar data type.
in Post.class.php your model directory you can define two override methods
setOptions($v)
{
parent::setOptions(serialize($v));
}
getOptions()
{
return unserialize($this->options);
}
Just like that.
In your view or action you can get all options with $post->getOptions() and you have an Array that contains all option related to your database record.

Resources