Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts

Thursday, January 16, 2014

Ruby, turn array of hashes into single hash

I have the following Array of Hashes:

a = [{:a => 1, :b => "x"}, {:a => 2, :b => "y"}]

I need to turn it into:

z={"x" => 1, "y" => 2} 

or:

z={1 => "x", 2 => "y"}

Can I do this in a clean & functional way?

Something like this:

Hash[a.map(&:values)] # => {1=>"x", 2=>"y"}

if you want the other way:

Hash[a.map(&:values).map(&:reverse)] # => {"x"=>1, "y"=>2}

incorporating the suggestion from @squiguy:

Hash[a.map(&:values)].invert

Thursday, October 10, 2013

To display the searched item in the same page

The following code present in srches_controller

def index   @srches = Srch.all   respond_to do |format|     format.html # index.html.erb     format.json { render :json => @srches }end. ..def search    @srch=Srch.find(:all,                :conditions => ["name LIKE ? OR address LIKE ?", "%#{params[:search]}%", "%#{params[:search]}%"])end

The searched item is now displayed in the new search page.
But I need to display the searched item in the same index page.
What is the solution?

You can pass parameter search to index page & search your results with:

def index  @srches = Srch.scoped  if params[:search].present?    @srches = @srches.where(['name LIKE ? OR address LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%"])  end  respond_to do |format|    format.html    format.json { render :json => @srches }  endend

or you can set scope in your model:

scope :search, lambda{|query|  if query.present?    where(['name LIKE ? OR address LIKE ?', "%#{query}%", "%#{query}%"])  end}

and call it in controller with:

@srches = Srch.search(params[:search])

Friday, October 4, 2013

rails input selected values from params to select_tag (multiple => true)

I want to keep the select_tag(:multiple => true) options to be selected which were selected by user once search is performed

<%= select_tag 'values[]', method_for_options_for_select, :class => 'some-class', :multiple => true, :size => 6 %>

Suppose a user select 4 values from the select tag then for values should be selected,
How can we pass this 4 values to the select_tag?

I tried using :selected => params['values[]'] yet this doesnt works for multiple true

Any assist will be appreciated

Ref this & options_for_select

Something like following

<%= select_tag 'values[]', options_for_select(@stores.map {|s| [s.store_name, s.store_id]}, @user.stores.map {|j| j.store_id}),:class => 'some-class', :multiple => true, :size => 6 %>