how to create dropdown from a hash in rails 3 - ruby-on-rails-3

In rails 3, how to create a Dropdown from hash
I have following code in my User class
class User
... other codes
key :gender, Integer # i use mongo db
class << self
def genders()
genders = {
'1' => 'Male',
'2' => 'Female',
'3' => 'Secret'
}
end
end
end
In the user form, i am trying to create a gender dropdown list
<%= f.collection_select nil, :gender, User.genders, :key, :value %>
but it complain
undefined method `merge' for :value:Symbol
So what is the proper way to create the dropdown?
Thanks

This should work:
<%= f.collection_select :gender, User.genders, :first, :last %>
Edit: Explanations:
collection_select will call each on the object you give (User.genders here) and the two methods (first and last here) on each object. It's roughly equivalent to something like this:
User.genders.each do |object|
output << "<option value=#{object.first.inspect}>#{h object.last}</option>"
end
When you call each on a Hash, it yields an Array of two values (the key and the value). These values can be retreived with the first and last methods.

Related

Concatenate field names in select

I have a form that allows you to select a facility by name then writes the id of the facility to a vale in the database.
<%= f.collection_select(:transfer_to_id, Facility.all, :id, :facility_name, {:include_blank => true}, {:class => 'select'})%>
I'd like to be able to select the facility name but to the right of the facility name display the facility_address in the form. I'm not sure how to do this, possibly an array of some sort or using a helper method.
If anyone can provide some help it would be appreciated.
Here is what ended up working properly for me by creating a Class method.
def facility_name_with_facility_address
"#{facility_name} | #{facility_address}"
end
This is untested so bear with me, but you need to add a method to your Facility model:
def facility_name_with_facility_address
facility_name << " " << facility_address
end
And then in your form you want to change the following:
<%= f.collection_select(:transfer_to_id, Facility.all, :id, :facility_name, {:include_blank => true}, {:class => 'select'})%>
To this:
<%= f.collection_select(:transfer_to_id, Facility.all, :id, :facility_name_with_facility_address, {:include_blank => true}, {:class => 'select'})%>

Advanced Rails ActiveRecord query using scope

I've been trying for a while to find the best way of querying for the desired result, but I always end up failing at some poing in the query.
Simplified database structure:
User:
id (integer)
first_name (string)
last_name (string)
CourseType:
title (string)
slug (string)
Course:
belongs_to :user
belongs_to :course_type
week (integer)
sold (float)
My controller is calling a scope:
#users = User.sales_results(week)
And here's the scope in my model:
scope :sales_results, lambda { |week|
joins(:courses => [:course_type])
.select("
users.id, users.first_name, users.last_name,
SUM(courses.sold) as total_sold,
COUNT(courses) as num_classes
")
.where("courses.week = ?", week)
.group('users.id')
}
This works fine, and I can use it in my template to show the total amount sold. Although I also want to show a second column where the value sold for some specific types of courses are summed up in. Something like this:
<% #users.each do |user| %>
<%= user.total_sold %>
<%= user.total_sold.where("course_types.slug IN ('H', 'S')") # not possible, but similar to what I desire %>
<% end %>
Update
I ended up adding another scope
scope :sales_results_for_types, lambda { |week, types|
sales_results(week).except(:group).where("course_types.slug IN (?)", types)
.group('users.id')
}
Then calling both scopes in my controller
#users = User.sales_results(...)
#users_filtered = User.sales_results_for_types(...)
Lastly iterating both results at the same time
<% #users.zip(#users_filtered).each do |user, filtered| %>
<%= filtered.total_sold %>
<%= user.total_sold %>
Until I figure out something better. Thanks guys for leading me on the right track.
If you are ok with having another query, you can use this
user.joins(courses: :course_type).sum(:sold, group: 'course_types.slug')
which will give you a hash where the keys are the slugs, and the values are the sums.

rails OR query based on multiple checkbox selections

This seems like it should be a common problem but I'm having trouble finding an answer. Basically I want to have a form with 10 or so checkboxes which I'm creating with check_box_tag. When the form is submitted I want to generate a query that return all records that match ANY of the checked selections. So, the number of checked selections will vary.
So, for example, if I have
class Book < ActiveRecord::Base
belongs_to :author
end
I want to generate something like
Book.where("author_id = ? or author_id = ?", params[authors[0]], params[authors[1]]) if there are two boxes checked, etc.
Thanks for any insight.
Will this work for you?
Book.where(author_id: [array_of_author_ids])
You need to collect author_ids from params first
I recently had to do something similar, this is how I achieved this. It's pretty clever (at least I think so. :))
I created a query model that serializes the query column (text field) in JSON. I use a form to get the query data from the user with selection fields.
class BookQuery < ActiveRecord::Base
has_many :books
# loop through each foreign key of the Book table and create a hash with empty selection
def self.empty_query
q = {}
Book.column_names.each do |column_name|
next unless column_name.ends_with?("_id")
q.merge column_name => []
end
end
end
I'm using Author as an example below:
<%= form_for #book_query do |f| %>
<% for author in Author.all %>
<%= check_box_tag "book_query[query][author_ids][]", author.id, false%>
<%= author.name %>
<% end %>
<%= f.submit "Save Query" %>
<% end %>
When this form is submitted you ended up with parameters like this:
When the form is submitted it generates this parameter:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XXXXXXXXXXX", "book_query"=>{"query"=>{"author_ids"=>["2", "3"]}}, "commit"=>"Save Query"}
Now in the BookQuery controller's create action you can just do what create function always does:
def create
#book_query = BookQuery.build(params[:book_query])
if #book_query.save
flash[:success] = "Book query successfully saved."
redirect_to ...
else
flash[:error] = "Failed to save book query."
render :new
end
end
But by default rails serializes the data in hash type:
1.9.3p194 :015 > pp BookQuery.find(9).query
BookQuery Load (0.7ms) SELECT "book_queries".* FROM "book_queries" WHERE "book_queries"."id" = $1 LIMIT 1 [["id", 9]]
"--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\nauthor_ids:\n- '2'\n- '3'\n"
=> "--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\nauthor_ids:\n- '2'\n- '3'\n"
In BookQuery model, add the following:
serialize :query, JSON
But rail would change the IDs to string:
1.9.3p194 :018 > query = JSON.parse(BookQuery.find(10).query)
BookQuery Load (0.5ms) SELECT "book_queries".* FROM "book_queries" WHERE "book_queries"."id" = $1 LIMIT 1 [["id", 10]]
=> {"author_ids"=>["2", "3"]}
1.9.3p194 :019 > query["author_ids"]
=> ["2", "3"]
What I did then is override the attribute accessors in BookQuery model:
The below has to be done because the hash returns strings, not ids in integer.
def query=(query)
query.each_pair do |k, v|
if query[k].first.present?
query[k].map!(&:to_i)
else
query.except!(k)
end
end
write_attribute(:query, query)
end
# just want to avoid getting nil query's
def query
read_attribute(:query) || {}
end
To find book with this query, you can simply add this function to your Book model:
def self.find_by_book_query(book_query, options = {})
options[:conditions] = book_query.query
find(:all, options)
end
Now you get a customizable query string based on the model definition Book and everything works like the Rails way. :)

Rails filtering with acts_as_taggable gem

I am working the acts-as-taggable-on gem and have a question about how to filter down search results based on tags users select. Here's an abridged look at my controller:
class PhotosController < ApplicationController
def index
#photos = Photo.where(["created_at > ? AND is_approved = ?", 1.months.ago, true])
#tags = ["Animals", "Architecture", "Cars", "Flowers", "Food/Drink", "General", "Landscape", "Mountains", "Nature"]
end
def search_by_tag(tag)
#photos = Photo.where('tagged_with LIKE ?', tag)
end
end
Photos/index
<% #tags.each do |tag| %>
<%= link_to tag, {:search_by_tag => tag}, :class => "tag" %>
<% end %>
This lists out all of the tags from the hash #tags defined in index, but clicking them doesn't actually filter anything down. Here's a look at what clicking one of those links produces in the log:
Started GET "/photos?search_by_tag=Animals" for 127.0.0.1 at Sun Oct 09 17:11:09 -0400 2011
Processing by PhotosController#index as HTML
Parameters: {"search_by_tag"=>"Animals"}
SQL (0.5ms) SELECT name FROM sqlite_master WHERE type = 'table' AND NOT name = 'sqlite_sequence'
The result I want is for the page to display only Photos that are tagged_with whichever tag was clicked on. I can't quite figure out how to accomplish this.
(Side-question: I can't seem to find a way to list out all of the tags from the tags table that acts-as-taggable-on generated. Doing something like Photo.tagged_with or Photo.tags doesn't work. I am able to see the "tags" table the gem created, and the entries inside of it; I'm just not really clear how to handle that using this gem)
Any thoughts greatly appreciated.
UPDATE
I've updated my code and am a bit closer.
class PhotosController < ApplicationController
def search_by_tag
#photos = Photo.tagged_with(params[:tag_name])
end
photos/index
<% Photo.tag_counts_on(:tags).map(&:name).each do |tag| %>
<%= link_to tag, {:action => 'search_by_tag', :tag_name => tag}, :class => "tag" %>
<% end %>
I believe this is closer, but still working through this...
You have a number of errors in your code:
Your link_to call is actually calling the index action.
Your search_by_tag method is expecting an argument, where it should be using the params hash to access the parameters passed to it in the web request.
tagged_with is a class method added by acts_as_taggable_on, not a field in your table - therefore you can't use it in the where method like you have done.
Finally, to get all the tag names: Photo.tag_counts_on(:tags_or_whatever_you_tagged_on).map(&:name)
Take a look at the acts_as_taggable_on documentation and you'll see examples of how to use tag_counts_on and tagged_with.
As for the Rails things: http://guides.rubyonrails.org/ http://railsforzombies.org/ and/or http://railscasts.com/

Rails 3 custom validation: Highlighting offending fields

I'm writing my first custom rails validation, and would like to tag the offending class with an html "error" class if they return false - I can't quite figure out how to do it. Relevant validation code below - any help appreciated.
(If it makes a difference, I'm using jQuery)
validates_each :shop do |record, attr, value|
shopvar = record.shops.map{ |s| s.email.downcase.strip }
if shopvar.count != shopvar.uniq.count
record.errors.add(attr, 'has the same email address entered more than once')
#record.errors[attr] << "You have entered this shop in the form twice"
end
end
So in your form you'd have something like this for an input field
<%= form.text_field :title %>
Since errors is a hash you could use the "include?" method like so...
errors.include?(:title)
This tells you that there's something wrong with this field. Now all you need to do is style it.
Whack on a ternary operator asi...
<% css_class = errors.include?(:title) ? "highlight_error_class" : "no_problem_class" %>
<%= form.text_field :title, :class => css_class %>
Done.