Passing in variables for preselection in a selection form (Ruby on rails)
I'm going through the example in the AROR book: http://media.pragprog.com/titles/rails3/code/e1/views/app/views/test/select.rhtml
<% @user = "cat"
def @user.id
4
end
<% form_for :user do |form| %>
<%= form.select(:name, %w{ Andy Bert Chas Dave Eric Fred }) %>
<% end %>
In this e开发者_JAVA百科xample, looks like @user.id is hardcoded to return 4. I tried something like:
@temp = 4
def @user.id
@temp
end
This didn't work... How do I return a non global variable for this particular function?
You must understand that when you do "def @user.id" you are actually defining a method on the singleton class associated with the @user object (the singleton class is also known as the "eigenclass" or "shadow class"). So what are doing is equivalent to this:
@temp = 4
class << @user
def id
@temp
end
end
As you can see above, the @temp inside the id method definition is a regular instance variable, but it is associated with the singleton class. In other words the @temp inside the id definition is different from the @temp outside. You can deal with this by directly setting the inside @temp, like so:
@user.instance_variable_set(:@temp, 4)
def @user.id
@temp
end
Let me know if that helps, or you have any further questions about how the singleton class works.
This question really has nothing to do with forms, or even Ruby on Rails. It's pure Ruby.
def @user.id; end
is a so-called singleton method (which you can read more about here). Now, by default, you cannot access instance variables (eg. @temp
) inside a singleton method.
There are some ways to get around this, but unless you specifically want to create a singleton method in your view (and why would you?), I'd recommend an alternative way of setting a preselect value. With your example, it should be as simple as:
<% form_for :user do |form| %>
<%= form.select(:name, %w{ Andy Bert Chas Dave Eric Fred }, {:selected => @temp}) %>
<% end %>
As a sidenote; @var
is an instance variable in Ruby--not a global variable. Global variables start with a dollar-sign ($var
), but please don't use this unless you know what you're doing.
精彩评论