我在表单助手中的虚拟属性出现奇怪的错误。Rails - 表单助手中的虚拟属性
我的模型看起来是这样的:
class Folder < ActiveRecord::Base
...
# VIRTUAL ATTRIBUTES
def parent_name
self.parent.name
end
def parent_name=(name)
self.parent = self.class.find_by_name(name)
end
...
end
我使用HAML和SimpleForm。当我使用我的表格时,像这样...
= simple_form_for [@collection, form], :html => { :class => 'full' } do |f|
= f.input :name
= f.input :description
= f.submit
...它完美地工作。但是,如果我尝试访问虚拟属性是这样的...
= simple_form_for [@collection, form], :html => { :class => 'full' } do |f|
= f.input :name
= f.input :parent_name
= f.input :description
= f.submit
...我得到这个错误:
NoMethodError in Folders#index
Showing ... where line #3 raised:
undefined method `name' for nil:NilClass
Extracted source (around line #3):
1: = simple_form_for [@collection, form], :html => { :class => 'full' } do |f|
2: = f.input :name
3: = f.input :parent_name
4: = f.input :description
5: = f.submit
有什么建议?
当表单呈现时,它将首先尝试检索值,并且失败,因为还没有父类。这确实是修复! – nathanvda 2011-03-05 00:11:17
美丽。谢谢。 – Andrew 2011-03-05 00:28:40