Ruby on rails 具有未定义方法的虚拟属性问题

Ruby on rails 具有未定义方法的虚拟属性问题,ruby-on-rails,ruby,attributes,virtual,Ruby On Rails,Ruby,Attributes,Virtual,我过去使用过虚拟属性,但我似乎无法克服这一点,我知道答案可能就在眼前 我有一个这样的模型: 模型确认.rb new.html.erb 错误 未定义的方法“confirmation=”用于# 在控制台预订中。通过确认令牌查找令牌(令牌)和给定的令牌工作得非常好 有什么想法吗?建议?我认为应该是: def confirmation_token=(token) @confirmation = Booking.find_by_confirmation_token(token) end 或者您应

我过去使用过虚拟属性,但我似乎无法克服这一点,我知道答案可能就在眼前

我有一个这样的模型:

模型确认.rb new.html.erb 错误 未定义的方法“confirmation=”用于#

在控制台预订中。通过确认令牌查找令牌(令牌)和给定的令牌工作得非常好


有什么想法吗?建议?

我认为应该是:

def confirmation_token=(token)
    @confirmation = Booking.find_by_confirmation_token(token)
end
或者您应该取消注释
attr\u accessible:confirmation
或定义
\confirmation
\confirmation=
类确认class Confirmation < ActiveRecord::Base
  belongs_to :bookings

  #attr_accessible :confirmation, :confirmation_token
  #attr_accessible :confirmation

  def confirmation_token
    @confirmation.confirmation_token if @confirmation
  end

  def confirmation_token=(token)
    @confirmation = Booking.find_by_confirmation_token(token)
  end

end
属于:预订 #属性可访问:确认,:确认\u令牌 #可访问属性:确认 def确认令牌 @confirmation.confirmation\u令牌,如果@confirmation 结束 def确认_令牌=(令牌) @确认=预订。通过确认令牌(令牌)查找 结束 结束
这起作用了。。。然而,仅仅是发现了可访问的属性:确认,没有。self.confirmation仍然返回未定义的方法…

您真正需要的是attr\u访问器:confirmation。attr\u accessible和attr\u accessor之间有区别

attr_accessor :confirmation

def confirmation
  @confirmation
end

def confirmation=(value)
  @confirmation = value
end
由于这是一种非常常见的模式,ruby为此引入了助手方法


另一方面,Attr_accessible是rails方法,它标志着某些字段可以批量更新。

这很奇怪。我以前也试过同样的方法。。。用@代替self。。。但它不起作用。但这次它做到了。还是不知道发生了什么变化。。Thank.attr#u accessible仅适用于通过模型属性进行的批量分配。它没有定义getter/setter。attr_访问器正在这样做。
def confirmation_token=(token)
    @confirmation = Booking.find_by_confirmation_token(token)
end
class Confirmation < ActiveRecord::Base
  belongs_to :bookings

  #attr_accessible :confirmation, :confirmation_token
  #attr_accessible :confirmation

  def confirmation_token
    @confirmation.confirmation_token if @confirmation
  end

  def confirmation_token=(token)
    @confirmation = Booking.find_by_confirmation_token(token)
  end

end
attr_accessor :confirmation
def confirmation
  @confirmation
end

def confirmation=(value)
  @confirmation = value
end