
[英]How to create a method in controller for the IF condition to call in the view in ruby on rails?
[英]How to create 'instance'.'method' call possible - Ruby on Rails
我在RoR方面还很陌生,现在我正面临一个问题。 我正在实施一个出勤系统,并且应用程序中有事件资源。 我想做的是可以调用event.color(在Event的实例上)并找回经典的CSS颜色字符串(如#2EAC6A)。 如果可能的话,我不想在数据库中创建新的列或表。 这意味着最好由红宝石本身来处理此颜色变量。
我想根据事件的类型设置事件的颜色。 我在想的是这样设置颜色的方法:
class Event < ActiveRecord::Base
after_create :set_color
...
def set_color
case self.type
when type1
#Here I want to set the color for event of type1
when type2
#Here I want to set the color for event of type2
when ....
.
.
end
end
这只是用于设置颜色(但我仍然不确定它是否起作用...),但是我不知道如何在没有数据库的情况下为每个事件保留颜色变量,以及如何使Event.color方法调用成为可能。 我正在使用RoR v 3.2.14
拜托,我将很高兴为您提供任何帮助。 谢谢你,祝你有美好的一天!
JS
如果您的颜色从未改变-或每个type1始终与另一种type1具有相同的颜色,则可以在模型或位掩码中使用不同的CONSTANTS。
使用常量的示例:
class Event < ActiveRecord::Base
COLOR_TYPE1 = "#2EAC6A"
COLOR_TYPE2 = "#000000"
COLOR_TYPE3 = "#ffffff"
def color
case self.type
when type1
COLOR_TYPE1
when type2
COLOR_TYPE2
when type3
COLOR_TYPE3
else
raise "for this type is no color defined!"
end
end
end
您不需要设置颜色-因为您没有属性颜色。 简单地使用普通方法即可根据实例的类型返回正确的颜色。
没有常量的另一种选择:(我认为这种方法比上述方法更好:-))
class Event < ActiveRecord::Base
def color
case self.type
when type1
"#2EAC6A"
when type2
"#000000"
when type3
"#ffffff"
else
raise "for this type is no color defined!"
end
end
end
如果每个实例具有不同的类,则不能使用常量,而可以直接定义颜色:
class Type1 < Event
def color
"#2EAC6A"
end
end
def Type2 < Event
def color
"#000000"
end
end
def Type3 < Event
def color
"#ffffff"
end
end
不同的类的优点是,您可以处理所有直接取决于父类“事件”的子类中的类型的内容。 你有主意吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.