Grouping attributes together rails 3 - ruby-on-rails

I have a destination model with following attributes :-
1) Continent 2) Country 3) City
I am doing something like this in the view :-
-#destinations.each do |d|
=d.continent
=d.country
=d.city
I the result to be grouped together i.e :- I want all the cities which are in a country together and all the country which are in a continent. I want to display something like this :-
Asia
India
New delhi
Lucknow
China
Beijing
Europe
Greece
How to I go about achieving this thing?

Look into the group_by method of the Enumerable class.
The idea would be to try something like
#destinations.group_by(&:continent).each do |continent, ds_per_continent|
# print continent
- ds_per_continent.group_by(&:country).each do |country, ds_per_country|
# print country
- ds_per_country.each do |destination|
# print destination.city

Related

Searching for specific characters in user input

Within my house table I have a postcode for each house.
I also have an index view for my housing table that contains a table which contains headings such as 'Name', 'Address', 'State'. I was looking to integrate a text_field_tag that would allow user's to input the 9 digits of a postcode in order to filter the table to only show the house with that postcode. However, I also want the user to be able to input the first 4 digits of their postcode e.g. '7644' and it would display all houses that begin with '7644' e.g. two records one with the postcode of the '76444-5645' and '76443-123'. Ideally I would apply logic through my '#search' variable within my houses controller. However I am up to any ideas or tips.
In order to instantiate the house model I would use #house = House.all
I'll be honest I don't know where to begin with this. I have arel_sql in my system so I assume that would be used to query for the search.
It depends on how your models/controllers are defined but you're probably looking for the SQL operator LIKE + '%', which allows you to search for a pattern in a given column. Example:
LIKE Operator
Description
WHERE CustomerName LIKE 'a%'
Finds any values that start with "a"
Assuming you're using ActiveRecord and your model is House, it wouldn't event need to instantiate all houses. Your code would look something like this:
postcode = '7644'
#houses = House.where('postcode LIKE ?', "#{postcode}%") # this returns where the postcode starts with '7644'
another similar SO answer for reference

Ruby On Rails Dynamic Where Search

I am using postgres for the db.
Service Address Controller contains this line
#service_addresses = ServiceAddress.where("customer_id =?" , params[:customer_id]).search(params[:search])
Service Address Model Method:
def self.search(query)
where("street LIKE ? OR city LIKE ?", "%#{query.to_s}%","%{query.to_s}%")
end
In my view I have a search bar that sends params
service_addresses?utf8=✓&search=123+Echo+Dr+New+York
Lets assume I have two columns on my view Street & City
If I search 123 Echo Dr. New York it will NOT return a record where Street = 123 Echo Dr. and the City = New York
However, if I simply search 123 Echo Dr. or 123 it will return all records that have that in the Street or City column. Similairly if I search New York it will return records that contain New York
I tried parsing out the search param into an array (successfully) and then using a loop to essentially build a string of "%#{parsed_query[i]}%" However when I tried to pass the string of binds to my where statement, but I got an error stating I have the wrong number of binds. It was treating my string variable as one bind.
Not able to use Data Tables gem!
Thank you SOF community.
Iterate over the tokens parsed from the query string to build up your query with ActiveRecord. Note that this will result in a SQL query many AND conditions.
#service_addresses = ServiceAddress.where("customer_id =?" , params[:customer_id])
parsed_query.each do |token|
#service_addresses = #service_addresses.search(token)
end
Update for case-insensitivity
To ignore case you can convert all strings to either uppercase or lowercase.
# Service Address Model Method:
def self.search(query)
where("upper(street) LIKE ? OR upper(city) LIKE ?", "%#{query.to_s.upcase}%","%{query.to_s.upcase}%")
end
Alternative
You may wish to look into document matching (full-text search). Postgres has some nice support for this. The topic is too much to cover here, but there are many resources online. A good place to start is the Postgres documentation
If I understand you problem, try this:
def self.search(keyword)
keyword_search = "%#{keyword.downcase}%"
where('lower(city) LIKE :search OR lower(street) LIKE :search', search: keyword_search)
end

Search four fields in YQL geo.places

We are currently using YQL to query geo data for towns and counties in the UK. At the moment, we can use the following query to find all towns named Boston:
select * from geo.places where text="boston" and placeTypeName="Town"
Demo
The issue is, that we would like to specify the county and country to generate more specific results. I have tried the following query, but it returns 0 results:
select * from geo.places where (text="boston" and placeTypeName="Town") and (text="lincolnshire" and placeTypeName="County")
Demo
How can I query 3 field types to return the results I need? Essentially, we would like to query the following fields:
text and placeTypeName="Town"
text and placeTypeName="County"
text and placeTypeName="Country"
This may be an option maybe:
https://developer.yahoo.com/blogs/ydnsevenblog/solving-location-based-services-needs-yahoo-other-technology-7952.html
As it mentions:
Turning text into a location
You can also turn a text (name) into a location using the following code:
yqlgeo.get('paris,fr',function(o){
alert(o.place.name+' ('+
o.place.centroid.latitude+','+
o.place.centroid.longitude+
')');
})
This wrapper call uses our Placemaker Service under the hood and automatically disambiguates for you. This means that Paris is Paris, France, and not Paris Hilton; London is London, England, and not Jack London.

How to check if a country belongs to Europe

I'd like to check if the country name provided belongs to Europe.
Does anyone know of a list of european countries that can be used in a Ruby project?
I'd like to do something like this:
spain = Country.named('Spain')
spain.parent # => 'Europe'
japan = Country.named('Japan')
japan.parent # => 'Asia'
https://github.com/jim/carmen/ lets me list subregions of a country, but not a country's parent.
Try that gem if you really need whole gem for this. You should be able to do:
Country.find_all_countries_by_region('Europe')
to get countries in Europe.
Check out the Wikipedia article for a complete list. http://en.wikipedia.org/wiki/List_of_European_countries

Rails - showing grouped records

I have some records:
Type Name
2 USA
2 USA
3 Canada
4 Mexico
1 Canada
2 Mexico
3 USA
I just want to show the list of unique types: 1,2,3,4 (no double, triple records).
I was trying to do something like that in my view:
<% #Orders.group(:type).each do |order| %>
... showing in the table
<% end %>
But I got following error:
undefined method `group' for #
Do I need to add some method in the controller/model?
Why - if .each method works ok in the view, group doesn't?
It's a little unclear what exactly you are trying to return/display, but I think you might want to look at #group_by (http://api.rubyonrails.org/classes/Enumerable.html#method-i-group_by).
Alternatively, look at some of the aggregate methods on this page: http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-calculate
Usually an instance variable is lowercase, that is #orders not #Orders. The error is telling you that it cannot find a method group for whatever it is that's in #Orders, so that's what you would focus on.
Once that's sorted out, you may want to use either the ActiveRecord distinct operator, or, if your records are in ruby, use .uniq on a collection (i.e. array).

Resources