简体   繁体   中英

RAILS - User has more than one category

I have a rails app that I'm trying to make an association with USERS (there are many) and Categories (there are 3, which I seeded). Each category has a name and an ID...

When I try to get users to edit their category, the form comes up blank.

The code I'm using for users to select their category is as follows :

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

(i have also tried Category.all.collect)

Here is what my SCHEMA looks like

 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"

and here are my Models,

class User < ApplicationRecord
    has_many :categories

class Category < ApplicationRecord
  validates :catname, presence: true

  has_many :specialties
  belongs_to :user

You can try something like that.

<%= 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 %>

or create a field categories in user, then:

<%= form.select :categories, Category.all.collect {|x| [x.name, x.id]}, {}, :multiple => true%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM