RAILS - 用户有多个类别

时间:2018-04-23 19:48:38

标签: ruby-on-rails migration models has-many relationships

我有一个rails应用程序,我正在尝试与USERS(有很多)和类别(有3个,我播种)建立联系。每个类别都有一个名称和一个ID ......

当我尝试让用户编辑他们的类别时,表单会显示为空白。

我用于用户选择其类别的代码如下:

    <%= form_for (@user) do |f| %>
   <%= f.select :categories, @user.categories.all, {multiple: true} %>

(我也尝试过Category.all.collect)

这是我的SCHEMA的样子

 create_table "categories", force: :cascade do |t|
    t.string "catname"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "user_id"
    t.index ["user_id"], name: "index_categories_on_user_id"
  end


  create_table "specialties", force: :cascade do |t|
    t.string "specname"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "category_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.integer "category_id"

这是我的模特,

class User < ApplicationRecord
    has_many :categories

class Category < ApplicationRecord
  validates :catname, presence: true

  has_many :specialties
  belongs_to :user

1 个答案:

答案 0 :(得分:1)

你可以试试这样的东西。

concat [ [1], [], [3], [], [5] ] = [1] ++ [] ++ [3] ++ [] ++ [5] = [1,3,5]

或 在用户中创建一个字段类别,然后:

<%= hidden_field_tag "user[category_ids][]", nil %>
<% Category.all.each do |category| %> 
   <%= check_box_tag "user[category_ids][]", category.id, @user.category_ids.include?(category.id), id: dom_id(category) %>
   <%= label_tag dom_id(category), category.catname %> <br>  
 <% end %>
相关问题