0

我试图找出这个HABTM关系问题以存储在我的数据库中的用户的利益。利益表有标识和名称不同利益的名单(即:ID = 1,名称=“音乐”)Rails - HABTM关系...存储来自用户的复选框值

我有一个用户模式=> user.rb

has_and_belongs_to_many :interests 

和利益model => interest.rb

has_and_belongs_to_many :users 

现在我试图编辑或更新用户从复选框列表中选择兴趣。 控制器看起来像这样=>

def edit 
#@interests = Interest.find(:all) 

    @title = "Edit Interest" 
    @user = User.find(session[:user_id]) 
    @user.interest ||= Interest.new 
    interest = @user.interest 
    if param_posted?(:interest) 
     if @user.interest.update_attributes(params[:interest]) 
      flash[:notice] = "Changes saved." 
      redirect_to :controller => "users", :action => "index" 
     end 
    end 
end 

和param_posted函数看起来像这样

def param_posted?(sym) 
    request.post? and params[sym] 
    end 

视图逻辑看起来像这样:

<% for interest in @interest %> 
<div> 
<%= check_box_tag "user[interest_id][]", interest.id, @user.interests.include (interest) %> 
<%= interest.name %> 
</div> 
<% end %> 

我想一切都显得洁净,但是当我运行视图我得到的错误:

NoMethodError在InterestController#编辑 - 未定义的方法`兴趣'为#用户:0x4797ddc

我需要创建一个单独的模型/表连接用户的兴趣事件? Like InterestsofUsers(id,user_id,interest_id)?我以为HABTM关系将不再需要为...

困惑

回答

5

有几个问题。首先,您需要为兴趣和用户创建连接表。它的名字是两个表的组合,按字母顺序排列。它不能有主键。下面是一个例子:

class CreateInterestsUsersJoinTable < ActiveRecord::Migration 
    self.up 
    create_table :interests_users, :id => false do |t| 
     t.integer :interest_id 
     t.integer :user_id 
    end 
    end 

    self.down 
    drop_table :interests_users 
    end 
end 

命名连接表这种特定的方式是Rails知道如何自动找到它。

另外,请记住,用户没有一个的兴趣,用户有很多。这就是为什么没有@user.interest方法。有一个@user.interests方法,该方法返回该用户的所有兴趣的数组,您可以根据需要循环使用该数组。

除此之外,我真的会让你的控制器更加RESTful。该编辑操作尝试处理至少2种不同的请求,编辑和更新,当它们应该分开时。

修复此部分之后,发布有关如何使控制器更加宁静的另一个问题,并且我或其他人可以帮助您。对于那些在未来搜索stackoverflow数据库的人来说,最好将这两个问题保存在单独的问题中。

UPDATE:关于Rails的许多一对多的关系问题已经拿出往往不够,我编写了一个名为basic many-to-many associations解释如何使用habtm VS has_many :through的文章,以及它们之间的差异。

-1
  1. 连接表 - interests_users
  2. 用户.... to_many,所以它是多元的,你需要做有一个复选框列表
  3. 尝试坚持REST风格的约定:)后应该去更新方法
+0

我想,这真的只是总结点换点的答案,我给了一个小时前。 – 2010-01-30 02:26:46

+0

是的,用更少的话说... 并不意味着以任何方式踩你的观点,只是为了总结... – Devenv 2010-01-30 03:34:24