Rails - HABTM 关系...存储用户的复选框值

发布于 2024-08-19 19:51:29 字数 1362 浏览 8 评论 0 原文

我试图找出这个 HABTM 关系问题,以便将用户的利益存储在我的数据库中。兴趣表有一个包含 id 和名称的不同兴趣列表(即: 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 关系将消除这种需要......

困惑

Im trying to figure out this HABTM relationship issue to store in the interests of users within my database. The interests table has a list of different interests with id and name (i.e: id=1 , name = 'Music')

I have a users model => user.rb

has_and_belongs_to_many :interests

and an interests model => interest.rb

has_and_belongs_to_many :users

Now I'm trying to edit or update the users choice of interests from a list of checkboxes.
The controller looks like so =>

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

and the param_posted function looks like this

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

The view logic looks like this:

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

I thought everything looked kosher but when I run the view I get the error :

NoMethodError in InterestController#edit
- undefined method `interest' for # User:0x4797ddc

Do i need to create a separate model/table that connects the interest of users to events?
like InterestsofUsers ( id, user_id, interest_id)? I thought the HABTM relationship would eliminate the need for that...

Confused

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清旖 2024-08-26 19:51:29

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

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。该编辑操作试图处理至少两种不同类型的请求,即编辑和更新,而它们应该是分开的。

修复此部分后,请发布另一个有关如何使您的控制器更加安静的问题,我或其他人可以帮助您。最好将这两个问题放在单独的问题中,以便将来搜索 stackoverflow 数据库的人。

更新:关于 Rails 中多对多关系的问题经常出现,我写了一篇名为 基本多对多关联 解释如何使用 habtmhas_many :through< /code>,以及它们之间的区别。

There are a couple issues. First, you do need to create a join table for interests and users. Its name is combination of the two tables, in alphabetical order. It must not have a primary key. Here's an example:

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

Naming the join table this specific way is how Rails knows how to find it automatically.

Also, remember that a user doesn't have one interest, a user has many. That's why there's no @user.interest method. There is a @user.interests method, which returns an array of all the interests of that user, which you can cycle through as needed.

Aside from that, I'd really make your controller more RESTful. That edit action is trying to handle at least 2 different kinds of requests, edit AND update, when they should be separate.

After you get this part fixed, post another question about how to make your controller more restful, and I or someone else can help you there. It's better to keep the two issues in separate questions for those who search the stackoverflow database in the future.

UPDATE: questions about many-to-many relationships in Rails have come up often enough that I wrote an article called basic many-to-many associations to explain how to use habtm vs has_many :through, and the differences between them.

画▽骨i 2024-08-26 19:51:29
  1. 连接表 -interests_users
  2. 用户有...to_many,所以它是复数,您需要在那里创建一个复选框列表
  3. 尝试遵守 RESTful 约定:) 帖子应该转到更新方法
  1. join table - interests_users
    1. user has....to_many, so it's plural, you'll need to make there a list of checkboxes
    2. try to stick to RESTful conventions :) post should go to update method
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文