以下是我当前的代码。我删除了理解问题不需要的部分。
设置模型
class Setting < ActiveRecord::Base
attr_accessor :program_id, :session_types
def initialize
@session_types = Array.new
@program_id = ''
end
end
设置 Controller
def new
@setting = Setting.new
puts @setting.session_types.instance_of? Array
end
设置 View
<%= form_for(@setting) do |f| %> #ERROR LINE
...
<% end %>
我收到这个错误:
ActionView::Template::Error (undefined method `[]' for nil:NilClass):
3: </h1>
4: <p>We need to get your booking page setup. Please select the Program you wish to put up for booking.</p>
5:
6: <%= form_for(@setting) do |f| %>
7: <% @programs.each do |program| %>
8: <%= f.radio_button(:program_id, program.program_id)%>
9: <%= label_tag(:program_name, program.name) %>
app/views/settings/new.html.erb:6:in `_app_views_settings_new_html_erb__94314060479739781_70294544827460'
@setting.session_types = Empty Array
调试时。
所以我尝试用一个没有数组属性的简单测试模型
替换Setting Model
,如下所示:
class Testing < ActiveRecord::Base
attr_accessor :program_id
end
查看是否是 Setting
的 Array
属性 session_types
导致了错误。似乎因为 Testing
,我在 form_for
行之后的行中收到错误,这应该是正确的。 (不需要这条线来理解问题)
我想我没有正确理解模型的 Array
属性的初始化。任何帮助理解为什么抛出错误的帮助将不胜感激!提前致谢! =D
最佳答案
试试这个
def initialize
super
@session_types = Array.new
@program_id = ''
end
您很少粘贴错误,但这是首先想到的。如果这没有帮助,请发布整个错误。
原因是你的Setting
类继承自ActiveRecord::Base
,调用super
首先调用parent的initialize
方法,这样你就可以向方法添加功能(扩展它)。如果没有 super
,您可以覆盖它,这意味着您可以用您的代码替换它默认执行的所有操作(例如连接到数据库、验证)。
关于ruby-on-rails - Rails 未定义方法 `[]' 为 nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31138328/