我试图找出这个 HABTM 关系问题,以便在我的数据库中存储用户的利益。兴趣表有一个带有 id 和 name 的不同兴趣列表(即: id=1 ,name = 'Music')
我有一个用户模型 => user.rb
has_and_belongs_to_many :interests
和一个兴趣模型 => 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 %>
我认为一切看起来都很干净,但是当我运行视图时,我得到了错误:
InterestController#edit 中的 NoMethodError - # User:0x4797ddc 的未定义方法“interest”
我是否需要创建一个单独的模型/表格来将用户的兴趣与事件联系起来?像 InterestsofUsers (id, user_id, interest_id)?我认为HABTM关系将消除对那个的需要......
使困惑