2010-07-24 46 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

回答