データベース内のユーザーの利益のために保存するために、この HABTM 関係の問題を理解しようとしています。興味テーブルには、ID と名前を持つさまざまな興味のリストがあります (例: id=1 、名前 = '音楽')
私はユーザーモデルを持っています=> 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の関係があれば、その必要がなくなると思っていました...
混乱している