我正在尝试允许user
在wiki
页面上创建wiki#edit
添加协作者。{/ p>
我在schema.rb
中有这个为collaborators
创建连接表:
create_table "collaborators", force: :cascade do |t|
t.integer "user_id"
t.integer "wiki_id"
end
然而,在我最初的迁移中,我确实为user
和wiki
ID添加了索引:
class CreateCollaborators < ActiveRecord::Migration
def change
create_table :collaborators do |t|
t.integer :user_id, array: true, default: []
t.integer :wiki_id
end
add_index :users, :id, unique: true
add_index :wikis, :id, unique: true
end
end
我在wikis#edit
页面上使用此erb尝试生成潜在合作者列表(松散地关注this Railcast):
<% if @wiki.private? %>
<%= f.label :collaborators, class: 'checkbox' %>
<%= @users.each do |user| %>
<%= check_box_tag "wiki[user_ids][]", user.id, @wiki.collaborators.include?(user.id) %>
<%= user.name %><br>
<% end %>
<% end %>
现在我在wikis_controller
uninitialized constant WikisController::Collaborator
中的指示行上收到错误:
class WikisController < ApplicationController
def edit
@wiki = Wiki.find(params[:id])
@users = User.all
collaborators = Collaborator.all <<<<<<<ERROR CALLED ON THIS LINE
end
我创建了一个空白collaborators_controller
,但由于代码全部发生在wikis#edit
页面中,因此我不知道该放入哪些内容。
任何人都可以帮我这样做吗?我可能会以错误的方式接近它......
答案 0 :(得分:0)
habtm关系适用于没有模型的简单连接表。您无法调用Collaborator,因为连接表中不存在导致错误的模型。
如果您需要模型,可以切换到has_many:通过关系并创建协作者模型。在has_many:through中,与纯连接表不同,您的协作者表需要具有主键/ id列。
除非与habtm保持联系,否则你可以这样调用协会:
# Check if associated users include user
@wiki.users.include?(user)
# Get all users associated with wiki
wiki.users
# Get all wikis associated with user
user.wikis
由于您没有对连接表使用rails命名约定,因此在模型中您需要指定连接表,如:
# models/wiki.rb
has_and_belongs_to_many :users, :join_table => :collaborators
# models/user.rb
has_and_belongs_to_many :wikis, :join_table => :collaborators