Ruby on rails 如何简化模型中的属性,使其向下折叠到rails中的同一字段中?
我有一个模型叫做消息。我在数据库中存储了一个名为time\u received\u或\u sent的字段。传入的消息具有接收时间,传出的消息具有发送时间。任何信息都不会同时包含两者。我是否可以将这些合并到一个模型中,以便在编辑时,接收到的时间和发送到的时间正好指向该字段?在我的模型中,有四种方法看起来非常无用Ruby on rails 如何简化模型中的属性,使其向下折叠到rails中的同一字段中?,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我有一个模型叫做消息。我在数据库中存储了一个名为time\u received\u或\u sent的字段。传入的消息具有接收时间,传出的消息具有发送时间。任何信息都不会同时包含两者。我是否可以将这些合并到一个模型中,以便在编辑时,接收到的时间和发送到的时间正好指向该字段?在我的模型中,有四种方法看起来非常无用 Model Message < ActiveRecord::Base ... def time_received=(time_received) time
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
尽管如此,如果这是最好的方法,那么我可以接受。您可以始终使用
alias\u方法
来折叠这些方法:
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
class消息
这对于避免同一方法的重复实现非常方便。您始终可以使用
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
Model Message < ActiveRecord::Base
...
alias_attribute :time_sent, :time_received_or_sent
alias_attribute :time_received: time_received_or_sent
end
class消息
这对于避免相同方法的重复实现非常方便。Model MessageModel Message < ActiveRecord::Base
...
alias_attribute :time_sent, :time_received_or_sent
alias_attribute :time_received: time_received_or_sent
end
...
别名属性:发送时间、接收时间或发送时间
别名属性:接收时间:接收时间或发送时间
结束
模型消息
原来alias_属性就是我要找的。很抱歉,如果你来这里是想得到答案。你可以随时添加这个作为结束它的答案。这是个好主意。我的声誉不足以在我发布后这么快就发表评论。现在我将作为答案发布。原来alias_属性就是我要找的。很抱歉,如果你来这里是想得到答案。你可以随时添加这个作为结束它的答案。这是个好主意。我的声誉不足以在我发布后这么快就发表评论。我现在就发布一个答案。