2010-02-14 47 views
1

嘿,我一直在使用has_and_belongs_to_many關係與Railscast Episode #17複選框示例。我有一些問題,現在一切工作順利,除非更新按鈕不起作用。更新與HABTM關係複選框的值 - Rails

編輯視圖看起來像這樣

<% form_for :users, :action => 'update' do |f| %> 
<% for interest in Interest.find(:all) %> 
<div> 
<%= check_box_tag "user[interest_ids][]", interest.id, 
       @user.interests.include?(interest) %> 
<%= interest.name %> 
</div> 
<% end %> 
<p> 
<%= f.submit 'Update' %> 
</p> 
<% end %> 

,並在控制器我....

def edit 
    @user = User.find(session[:user_id]) 
end 

def update 
    params[:user][:interest_ids] ||= [] 
    @user = User.find(session[:user_id]) 
    if @user.update_attributes(params[:user]) 
    flash[:notice]='User data was updated' 
    redirect_to :action => 'index' 
else 
    redirect_to :action => 'index' 
end 
end 

按鈕未事件做重定向......所以我不知道發生了什麼。在我的表單創建中有什麼搞砸了嗎?我不完全知道如何創建一個按鈕,並將其訪問方法與模型更新控制器等

我到處尋求幫助時,也許認爲這是因爲attr_accessible的,所以我說=>

attr_accessible :login, :email, :password, :password_confirmation, :interest_ids, :user 

我的用戶模型,但仍然沒有任何...我的想法爲什麼我的表單不提交?

回答

0

我發揮各地形式和正確的代碼是這個==>

<% form_for @user do |f| %> 
<% for interest in Interest.find(:all) %> 
<div> 
<%= check_box_tag "user[interest_ids][]", interest.id, @user.interests.include?(interest) %> 
<%= interest.name %> 
</div> 
<% end %> 
<p> 
<%= f.submit 'Edit' %> 
</p> 
<% end %> 

我很高興!所以顯然問題是:用戶應該是對象@user。

+0

這並不處理您將它們全部取消選中時的情況。 – 2012-05-01 21:18:08

+0

並沒有工作在最新版本的導軌 – 2012-10-18 17:29:14

+0

當我們有所有未經檢查的導軌將刪除所有關係 – antiqe 2013-01-21 11:13:49

0

check_box標籤必須是這樣的,它的工作:

<%= check_box "user", "user_interest_ids", {:checked => @user.interests.include?(interest), :name => 'user[interest_ids][]'}, interest.id, nil %> 

在我的廣告< - > ad_sizes我使用這個代碼的habtm關係:

<% @ad_sizes.each do |s| %> 
<li> 
<%= check_box "ad", "ad_size_ids", {:checked => @ad.ad_sizes.include?(s), :id => "ad_size_#{s.name}", :class => 'checkbox', :name => 'ad[ad_size_ids][]'}, s.id, nil %> 
<label class="checkbox" for="<%= "ad_size_#{s.name}" %>"><%= s.description %></label> 
</li> 
<% end %> 
+0

但不是代碼在railscast?我試過你的代碼,它沒有工作。沒有什麼東西還在更新中,我感覺它與表單中的某些東西有關,因爲它在按鈕點擊後沒有做任何重定向。 – ChrisWesAllen 2010-02-15 00:04:38

+0

代碼類似,爲true。順便說一句,你的'form_for'定義有錯誤。它應該讀取<%form_for:user,:action =>'update'do | f | %>' – 2010-02-15 00:07:56

+0

正確的我的意思是爲什麼沒有在railscast中的代碼?我調整了form_for,但你提供的代碼段似乎並沒有工作。我想知道爲什麼它還沒有做任何重定向。 – ChrisWesAllen 2010-02-15 00:27:41