Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass objects from one controller to another in rails?

I have been trying to get my head around render_to but I haven't had much success.

Essentially I have controller methods:

def first
  #I want to get the value of VAR1 here
end

def second
  VAR1 = ["Hello", "Goodbye"]
  render_to ??
end

What I can't figure out is how to accomplish that. Originally I just wanted to render the first.html.erb file but that didn't seem to work either.

Thanks

Edit: I appreciate the answers I have received, however all of them tend to avoid using the render method or redirect_to. Is it basically the case then that a you cannot pass variables from controller to controller? I have to think that there is some way but I can't seem to find it.

like image 301
Matthew Stopa Avatar asked Aug 17 '09 07:08

Matthew Stopa


1 Answers

It is not a good idea to assign the object to a constant. True this is in a global space, but it is global for everyone so any other user going to this request will get this object. There are a few solutions to this.

I am assuming you have a multi-step form you are going through. In that case you can pass the set attributes as hidden fields.

<%= f.hidden_field :name %>

If there are a lot of fields this can be tedious so you may want to loop through the params[...] hash or column_names method to determine which attributes to pass.

Alternatively you can store attributes in the session.

def first
  @item = Item.new(params[:item])
  session[:item_attributes] = @item.attributes
end

def second
  @item = Item.new(session[:item_attributes])
  @item.attributes = params[:item]
end

Thirdly, as Paul Keeble mentioned you can save the model to the database but mark it as incomplete. You may want to use a state machine for this.

Finally, you may want to take a look at the Acts As Wizard plugin.

like image 137
ryanb Avatar answered Sep 21 '22 06:09

ryanb