Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a model attribute to a Rails view using redirect_to

I'm trying to pass a model attribute to a view, after successfully setting it to a new value from inside an action in my controller. But this variable is always nil by the time it gets to the view, so I can't use it to conditionally display stuff. I should add that this attribute is not a field in the database. What am I missing/doing wrong?

Here is the code in my model:

attr_accessor :mode

#getter
def mode
 @mode
end

#setter
def mode=(val)
 @mode = val
end

...in the controller:

@report.mode = "t"
redirect_to edit_report_path(@report)

...and in my view:

<%= build_report(@report.mode) %>

...but this helper method never gets the variable I just set in the controller. It is nil. What gives? Clearly I'm missing something basic here because this seems like it should be straightforward. Any insight would be greatly appreciated. Thanks.

like image 871
deluxe_247 Avatar asked Mar 21 '09 23:03

deluxe_247


2 Answers

edit_report_path generates a URL with the ID of @report in it.

redirect_to essentially creates a whole new request, and goes to that URL. When it gets to edit, all it has is the ID. Usually that's fine - it looks up the object and keeps going, but of course it's not going to have the non-db field you set.

There are a couple ways to fix this. You can use :render instead to get to the edit page - then @report will have the field set.

@report.mode = "t"
render :action => edit and return

Or, you can make mode a database field.

like image 149
Sarah Mei Avatar answered Oct 23 '22 22:10

Sarah Mei


The problem here is in the redirect_to. When you redirect somewhere else all instance variables are lost. So when you set @report.mode = "t" it sets the attribute. But when you redirect that data is lost.

I am assuming the <%= build_report(@report.mode) %> is in edit_report.html.erb and the code from when you set 'mode' is not in the edit action. If this is the case you may be able to pass the report.mode to the edit action in the url like so:

 build_report(@report.mode, :mode => "t")
like image 22
vrish88 Avatar answered Oct 23 '22 20:10

vrish88