我有一个名为Message的模型。我有一个名为time_received_or_sent的字段存储在数据库中。传入的消息将具有time_recieved,并且传出的消息将发送时间。没有任何信息可以同时拥有。我可以在模型中组合这些,以便time_received和time_sent在编辑时只指向该字段吗?我的模型中有四种方法看起来很无用。
Model Message < ActiveRecord::Base
...
def time_received=(time_received)
time_received_or_sent = time_received
end
def time_received
return time_received_or_sent
end
def time_sent=(time_sent)
time_received_or_sent = time_sent
end
def time_sent
return time_received_or_sent
end
end
我希望更短的东西。
我正在寻找除了以外的东西:
def time_sent; time_received_or_sent; end
def time_received; time_received_or_sent; end
def time_sent=(time_sent); time_received_or_sent=(time_sent); end
def time_received=(time_received); time_received_or_sent=(time_received); end
虽然,如果这是最好的,那我就没事了。
答案 0 :(得分:1)
Model Message < ActiveRecord::Base
...
alias_attribute :time_sent, :time_received_or_sent
alias_attribute :time_received: time_received_or_sent
end
答案 1 :(得分:0)
您始终可以使用alias_method
将其折叠:
class Message < ActiveRecord::Base
def time_received=(time_received)
time_received_or_sent = time_received
end
alias_method :time_sent=, :time_received=
def time_received
time_received_or_sent
end
alias_method :time_sent, :time_received
end
这对于避免重复实现相同方法非常方便。