rajat_474 rajat_474 - 6 months ago 12
Ruby Question

Fetching array of data from DB using Rails 3

I want to access multiple columns using Rails 3.But it gave me the following error.


Error:


ArgumentError (wrong number of arguments (2 for 1)):
app/controllers/payments_controller.rb:13:in `check_type'


Check my below code.


payment_controller.rb:


class PaymentsController < ApplicationController

def payment
@payment=Vendor.new
respond_to do |format|
format.html
format.js
end

end
def check_type
if params[:commit]=="submit"
@vendor_type=PaymentVendor.where(:v_name => params[:v_name]).pluck(:type ,:Receipt_No)
@vendor_type.each do |vendor|

end
else
@v_name=Vendor.where(:s_catagory => params[:payment][:s_catagory] ).pluck(:v_name)
end
end
end


Actually i want to retrive data like below format.

@vendor_type=["Receipt_no":"type","Receipt_no":"type",.....]


Once these data will appear,I need how to access row values according to Receipt_No.Please help me to resolve this error.

Answer

Thanks to ActiveRecord >= 4 . pluck accepts multiple arguments so in

Rails 4: Your query will work

@vendor_type=PaymentVendor.where(:v_name => params[:v_name]).pluck(:type ,:Receipt_No)

Now as you are using Rails 3 which doesn't support multiple arguments to pluck then we can extend ActiveRecord::Relation itself like this:

put your file under config/initializers

# pluck_all.rb
module ActiveRecord
  class Relation
    def pluck_all(*args)
      args.map! do |column_name|
        if column_name.is_a?(Symbol) && column_names.include?(column_name.to_s)
          "#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(column_name)}"
        else
          column_name.to_s
        end
      end

      relation = clone
      relation.select_values = args
      klass.connection.select_all(relation.arel).map! do |attributes|
        initialized_attributes = klass.initialize_attributes(attributes)
        attributes.each do |key, attribute|
          attributes[key] = klass.type_cast_attribute(key, initialized_attributes)
        end
      end
    end
  end
end

Now in your controller you can pass multiple arguments to pluck like this:

# payment_controller.rb:
@vendor_type=PaymentVendor.where(:v_name => params[:v_name]).pluck_all(:type ,:Receipt_No)

Now you can use pluck_all in whole app. Hope this helps ;)

EDIT: Try below code if plcuk_all not worked:

@vendor_type = PaymentVendor.where(:v_name => params[:v_name]).map{|v|[v.type ,v.Receipt_No]}

Reference for more info: http://meltingice.net/2013/06/11/pluck-multiple-columns-rails/