Setting a variable for view

I’d like to set a value somewhere to let the view know if it is in “add
new” mode or “Update” mode. Depending on the mode, one line of text in
the view is to be presented differently (e.g. <% if updateMode == true
%>).

This brings up a couple of questions:
Where is the best place to store that value?
What is the proper way to set the value in the controller and to
retrieve it in the view?

Thanks in advance
—Michael

Hi –

On Sun, 22 Oct 2006, Michael S. wrote:

I’d like to set a value somewhere to let the view know if it is in “add
new” mode or “Update” mode. Depending on the mode, one line of text in
the view is to be presented differently (e.g. <% if updateMode == true
%>).

This brings up a couple of questions:
Where is the best place to store that value?
What is the proper way to set the value in the controller and to
retrieve it in the view?

Instance variables set in the controller are visible in the view. So
you would want to do:

Controller:

def my_action
@update_mode = true

end

View:

<% if @update_mode %>

<% end %>

(Note that you don’t need “== true”.)

Mind you, if you find yourself doing this a lot, it’s probably a sign
that you should reorganize your actions and views, perhaps by
splitting off an update sequence. I’ve run into situations like that
with @admin_session and other such flags: I realize eventually that
I’m really trying to squeeze two separate use cases into one view,
where it might be better, and scale better, to have a separate suite
of admin tools.

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

Hi Michael,

Michael S. wrote:

I’d like to set a value somewhere to let the view
know if it is in “add new” mode or “Update” mode.
Depending on the mode, one line of text in the view
is to be presented differently (e.g. <% if updateMode == true
%>).

The simplest approach might be to set an instance variable (e.g.,
@updateMode) in your controller and then do a check (e.g.,<% if
!@updateMode.nil? %>) in the view to figure out where you are.

hth,
Bill

If this specific issue as what you’re addressing, how about:

if @my_model_object.new_record?

do new code

else

do edit code

end

of if you are just changing the button names, use something like:

<%= submit_button(my_model_object.new_record? ? ‘add new’ : ‘update
now’) %>

Yes?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs