我已经定义了几个虚拟属性,同时定义了 setter 和 getters 方法:
class Post < ActiveRecord::Base
def shared_to_all
# evaluates some expression of the attribute privacy
end
def shared_to_friends
# evaluates some other expression of the attribute privacy
end
def shared_to_all=(bool)
# write_attribute( :privacy, ... )
end
def shared_to_friends=(bool)
# write_attribute( :privacy, ... )
end
end
到目前为止一切都很好,但我也想使用符号使这个虚拟属性可用,所以我可以做类似的事情@post= Post.first; @post[:shared_to_all]= true
[编辑:]
Ruby 方法是覆盖[]
和[]=
运算符,例如:
def [](shared_to_all)
shared_to_all
end
def []=(shared_to_all, bool)
self.shared_to_all= (bool)
end
但这似乎破坏了 Rails 关系方法(那些由has_one
- has_many
- belongs_to
-has_and_belongs_to_many
指令带来的方法):例如 nowPost.first.author => nil
和Author.first.posts => []