在 Rails 中我有以下模型:
class Recipe < ActiveRecord::Base
attr_accessible :name , :description ,
:t_baking , :t_cooling , :t_cooking ,:t_rest
# other stuff here
end
将t_baking
、t_cooling
、t_cooking
、t_rest
设置为Time
。
所以在我看来,我想循环每个值。
<% ['cooking', 'baking', 'cooling' , 'rest'].each do |time| %>
<% time_of_recipe = @recipe.instance_variable_get("@t_#{time}") %>
<% if time_of_recipe.is_a? Time %>
<%= time_of_recipe.strftime "%H:%M" %>
<% else %>
<%= time_of_recipe %>
<% end %>
<% end %>
它不起作用,因为
@recipe.instance_variable_get("@t_cooking").class # give NilClass
但是
@recipe.t_cooking.class # give Time
为什么?
最佳答案
@recipe.instance_variable_get("@t_cooking")
返回nil
,因为@recipe
没有实例变量@t_cooking
。
它是您可以访问的 ActiveRecord 定义的一堆方法,但这些不是实例变量。
将其应用到您的代码中,您希望将其更改为:
time_of_recipe = @recipe.public_send("t_#{time}")
此外,保存单个字母的输入是没有意义的。
执行以下操作会更具可读性:
<% %w(t_cooking t_baking t_cooling t_rest).each do |time| %>
<% time_of_recipe = @recipe.public_send(time) %>
# ...
编辑
如果您想检查可用的实例变量(您希望使用 Rails 3.2,因此您的输出可能略有不同):
@recipe.instance_variables
#=> [:@attributes, <============ this one is of particular interest
# :@aggregation_cache,
# :@association_cache,
# :@readonly,
# :@destroyed,
# :@marked_for_destruction,
# :@destroyed_by_association,
# :@new_record,
# :@txn,
# :@_start_transaction_state,
# :@transaction_state
# ]
所以你会看到,它定义了一个实例变量@attributes
,它保存所有属性。
关于ruby-on-rails - ActiveRecord 对象是否没有属性的实例变量而只有方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39930793/