更新带有HABTM关系的checkbox的值 - Rails [英] update values of checkbox with HABTM relationship -- Rails

查看:144
本文介绍了更新带有HABTM关系的checkbox的值 - Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 Railscast第17集的复选框中的has_and_belongs_to_many关系。我有一些问题,现在一切都是工作流畅,除了更新按钮将不工作。

Hey guys I've been using the has_and_belongs_to_many relationship with checkboxes example from the Railscast Episode #17 . I had some problems and now everything is working kind of smoothly except the update button will not work.

编辑视图看起来像这样

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

并且在控制器中有....

and in the controller I have ....

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

按钮不是重定向...所以我不知道发生了什么。在我的表单创建有什么东西搞乱了吗?我不知道如何创建一个按钮,并让它访问控制器中的方法与模型更新等。

The button isn't event doing the redirect... so I dont know whats happening. Is there something in my form creation messing this up? I'm not exactly sure how to create an button and have it access the method in the controller with model updates and etc.

我环顾四周寻求帮助,并认为也许它是因为attr_accessible所以我添加=>

I looked around for help and thought maybe it was because of attr_accessible so I added =>

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

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

to my user model but still nothing...Any I idea why my form isn't submitting?

推荐答案

我使用的形式,正确的代码是==>

I played around with the form and the correct code is this ==>

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

I'm so happy! So apparently the problem was :user which should the be object @user.

这篇关于更新带有HABTM关系的checkbox的值 - Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆