0

我已经定义了几个虚拟属性,同时定义了 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 => nilAuthor.first.posts => []

4

1 回答 1

0

似乎应该这样做:

def [](attr)
  attr
end
def []=(attr, value)
  self.attr = value
end
于 2013-05-11T18:01:11.893 回答