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...
我有一个rails应用程序,我试图与USERS(有很多)和类别(有3个,我播种)。每个类别都有一个名称和一个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)
(我也尝试过Category.all.collect)
Here is what my SCHEMA looks like
这是我的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"
and here are my Models,
这是我的模特,
class User < ApplicationRecord
has_many :categories
class Category < ApplicationRecord
validates :catname, presence: true
has_many :specialties
belongs_to :user
1 个解决方案
#1
1
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%>
#1
1
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%>