下面的问题是关于为对象选择“attr_accessor”启用的属性。例如:
class Openhour < ActiveRecord::Base
belongs_to :shop
attr_accessor :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday
end
这允许我
week = Openhour.new
week.monday = "Open"
week.tuesday = "Closed"
我的问题:如何通过使用循环中的变量来选择attr_accessors?在下面的情况下,我会使用dayname
来选择attr_accessor
。
@schedules.each do |schedule|
%w(monday tuesday wednesday thursday friday saturday sunday).each_with_index do |dayname,dayname_index|
week.dayname = schedule.day == dayname_index ? "Open" : "Closed"
end
end
然而,这将导致
*** NoMethodError Exception: undefined method `dayname' for #<Model>
提前致谢!
答案 0 :(得分:0)
你可以使用
week.send("#{dayname}=", schedule.day == dayname_index ? "Open" : "Closed")
或者您可以像instance_variables
week.instance_variable_set("@#{dayname}", schedule.day == dayname_index ? "Open" : "Closed")