Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `each' for "#<Complaigns::ActiveRecord_Relation:0x00000003cfb4c8>":String

I have a model, called Complaign, with some other attributes along with the date of complaign (c_date).

In the ComplaignController, I have an index view, which displays all the complaigns. There is a filter which takes from date and to date. On filtering that, it works fine, and properly displays the complaigns fired on those dates.

Now I want the result of this query to be passed on to a different method, say export method.

I thought of passing this from the index view, since it is stored in @complaigns.

This is my index method:

def index
        if params[:from] && params[:to]
            from = params[:from].to_date
            to = params[:to].to_date
            @complaigns = Complaigns.where(:c_date => from..to)
        else    
      @complaigns = Complaigns.all
        end    
  end

In the index view, this is what I have written

<%= link_to "Export", {:controller => "complaigns", :action => "export", :complaigns => @complaigns}%>

This is the export method

def export
         @complaigns = params[:complaigns]
  end

Now, in the export view, when I do the follwing line:

@complaigns.each, I get this error--

undefined method `each' for "#<Complaign::ActiveRecord_Relation:0x00000003cfb4c8>":String

Now this is because, I think, there is no method each in String class. Is there any way, I can convert the String to Complaign type in the method export or while passing it from the index view, pass it as Complaign object instead of String? Is there any other way of doing this?

like image 685
inquisitive Avatar asked Oct 30 '22 23:10

inquisitive


1 Answers

You can't pass Ruby on Rails model objects directly in the controller parameters, you can pass their corresponding ids and then load the models from the database. HTTP / Ruby on Rails is stateless. If you always go to index before export, one way how to solve this might be:

<%= link_to "Export", {:controller => "complaigns", :action => "export", :complaigns => @complaigns.map(&:id)}%>

def export
         @complaigns = Complaigns.find(params[:complaigns])
end
like image 109
adamliesko Avatar answered Nov 15 '22 05:11

adamliesko