我是否需要连接表的模型或控制器?

时间:2012-09-24 15:07:34

标签: ruby-on-rails-3 forms controller jointable

我的第一个联接表遇到了多对多关系的问题。

class Category < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

我添加了一个联接表:

create_table "categories_users", :id => false, :force => true do |t|
  t.integer "category_id", :null => false
  t.integer "user_id",     :null => false
end

有人能指出我将用户添加到某个类别的表单示例吗?我是否需要为“categories_users”提供单独的restful控制器?我有一种冲动将方法添加到我的类别控制器“add user”,但我不确定这对于其他RESTful控制器是否明智。

1 个答案:

答案 0 :(得分:0)

我正在使用simple_form,我终于在文档中找到了该怎么做。所以使用simple_form,表单看起来像这样:

<%= simple_form_for [:admin, @festival, @category] do |c| %>
  <%= c.input :name %>
  <%= c.input :description, input_html: { cols: 100, rows: 3, class: "span6" } %>
  <%= c.input :takes_submissions %>
  <%= c.association :users, label_method: :full_name, label: "Choose curators" %>
  <%= c.button :submit %>
<% end %>

无需添加控制器或单独的表单。耶!