【发布时间】:2011-03-20 10:00:42
【问题描述】:
我刚开始学习 Rails(版本 3),我正在尝试创建一个用户注册表单,其中包含他们感兴趣的复选框选项,可能是 0 个或多个选项。我生成了一个用户脚手架和一个兴趣模型。我在 Postgresql 中为兴趣表播种了数据:
Table "public.interests"
Column | Type | Modifiers
------------+--------------------+------------------------------------------------
id | integer | not null default nextval('interests_id_seq'::regclass)
interest | character varying(40) |
created_at | timestamp without time zone |
updated_at | timestamp without time zone |
Indexes:
"interests_pkey" PRIMARY KEY, btree (id)
视图有:
<div class="form_row">
<label for="interest_ids[]">Interests:</label>
<% for interest in Interest.find(:all) do %>
<br><%= check_box_tag 'interest_ids[]', interest.id,
@model.interest_ids.include?(interest.id) %>
<%= interest.name.humanize %>
<% end %>
</div>
模型interest.rb 有:
class Interest < ActiveRecord::Base
has_and_belongs_to_many :users
end
用户控制器 users_controller.rb 有:
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @user }
end
end
当我查看我得到的页面时:
undefined method `interest_ids' for nil:NilClass
谁能告诉我怎么了?谢谢。
【问题讨论】:
-
@model 应该是什么?我没有看到它在任何地方定义。看起来可能应该是 @user 代替?另一个问题是您使用的是 HABTM,最好使用 Has Many Through。
-
一些问题: 1. 您显示的视图是针对哪个控制器的?我想它是针对 InterestsController.2 的。您的变量
@model应该是哪种类型?在视图中@model得到消息interest_ids,如果@model没有填写,则自动为nil。那应该解释错误消息。一些模型类必须实现interest_ids。 -
这个位
@model.interest_ids.include?(interest.id) %>帮助我解决了我的问题!我的表单没有重新加载设置或正确保存它们。所以,谢谢:)
标签: ruby-on-rails