How can you simplify attributes in a model that fold down into the same field in rails?
I have a model called a Message. I have a field called time_received_or_sent stored in the database. A message that is incoming would have a time_recieved and a message that is outgoing would have a time sent. No message would ever have both. Can I combine these in a model so that time_received and time_sent just point to that field when edited? I have four methods in my model that look pretty useless.
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_开发者_JAVA百科sent
end
end
I would prefer something much shorter.
And I'm looking for something other than:
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
Although, if this is the best possible, then I'm fine with it.
Model Message < ActiveRecord::Base
...
alias_attribute :time_sent, :time_received_or_sent
alias_attribute :time_received: time_received_or_sent
end
You can always use alias_method
to collapse these down:
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
This is handy for avoiding duplicate implementations of the same method.
精彩评论