1

大家好,我一直在使用 has_and_belongs_to_many 与Railscast Episode #17中的复选框示例的关系。我遇到了一些问题,现在一切都很顺利,除了更新按钮不起作用。

编辑视图看起来像这样

<% 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

到我的用户模型,但仍然没有......我知道为什么我的表单没有提交吗?

4

2 回答 2

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。

于 2010-02-15T00:41:32.373 回答
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 %>
于 2010-02-14T23:58:40.333 回答