2010-07-24 52 views
1

我刚刚开始了解Rails(第3版),并且我正在尝试为其兴趣创建一个带有复选框选项的用户注册表单,该表单可能是0个或更多选项。我生成了一个用户脚手架和一个兴趣模型。我播种的利益表PostgreSQL中的数据:从数据库填充Rails上的复选框

        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> 

(基于Checkboxes on Rails

模型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 

谁能告诉我有什么不对?谢谢。

+0

什么@model是应该是什么?我没有看到它在任何地方定义。它看起来也许应该是@user呢?另一个问题是你使用HABTM,在那里它最好使用Has Many Through。 – 2010-07-24 04:40:14

+0

Somequestions: 1.您显示的视图是哪个控制器?我想这是InterestsController.2 。你的变量'@ model'应该是哪一种?在视图中,'@ model'获得'interest_ids'消息,如果'@ model'没有被填充,它就会自动被'nil'。这应该解释错误信息。某些模型类必须实现'interest_ids'。 – mliebelt 2010-07-24 10:55:01

+0

这位@ @ model.interest_ids.include?(interest.id)%>'帮我解决了我的问题!我的表单没有重新加载设置或正确保存它们。那谢谢啦 :) – CJBrew 2014-06-03 20:59:41

回答