我目前有一個Rails應用程序,它允許用戶創建一個組並允許其他用戶加入該組。組「創建者」是該組的所有者,並且任何加入請求的成員都是成員。我希望用戶能夠創建只有一個組,但屬於很多(我認爲我已經捕獲了這種關係,但我有點不確定)。我需要一些幫助來了解我需要做什麼才能在用戶頁面上顯示組關聯。我應該如何創建一個組「show」頁面,以及如何在用戶「show」頁面上顯示組成員身份?我得到了SO的幫助,並跟隨了Railscast關於自我指涉關係的指導,幫助指導我建立關係。Rails - 用於創建用戶組的控制器問題
在此示例中,組稱爲Cliqs,成員資格由has_many:through控制。我使用Devise作爲用戶模型。
澄清我的問題:我是否正在捕獲我正試圖建立的關係?我將如何去允許用戶查看他們所屬的組?
另外,我不確定組創建者是否作爲組的成員關聯。我如何在我的模型/控制器中表現這一點?
這裏是我的代碼:
組型號:
class Cliq < ActiveRecord::Base
belongs_to :owner, class_name: 'User'
has_many :members, through: :cliq_memberships, source: :user
has_many :cliq_memberships
end
會員制模式:
class CliqMembership < ActiveRecord::Base
belongs_to :cliq
belongs_to :user
end
用戶模型:
class User < ActiveRecord::Base
has_one :owned_group, foreign_key: 'owner_id', class_name: 'Group'
has_many :cliqs, through: :cliq_memberships
has_many :cliq_memberships
.
.
.
end
組控制器:
class CliqsController < ApplicationController
def show
@cliq = Cliq.find(params[:id])
end
def new
@cliq = Cliq.new(params[:id])
end
def create
@cliq = Cliq.create(cliq_params)
if @cliq.save
redirect_to current_user
else
redirect_to new_cliq_path
end
end
def destroy
end
def cliq_params
params.require(:cliq).permit(:name, :cliq_id)
end
end
組成員控制器:
class CliqMembershipsController < ApplicationController
def create
@cliq = cliq.find(params[:cliq_id])
if @cliq_membership.save = current_user.cliq_memberships.build(:cliq_id => params[:cliq_id])
flash[:notice] = "Joined #{@cliq.name}"
else
#Set up multiple error message handler for rejections/already a member
flash[:notice] = "Not able to join Cliq."
end
redirect_to cliq_url
end
def destroy
@cliq = Cliq.find(params[:id])
@cliq_memberships = current_user.cliq_memberships.find(params[cliq_memberships: :cliq_id]).destroy
redirect_to user_path(current_user)
end
end
我的用戶顯示頁面:
<h1> <%= @user.username %> </h1>
<h2>Cliqs</h2>
<%= link_to "Create Cliq", new_cliq_path %>
<ul>
<% for cliq_membership in @user.cliq_memberships %>
<li>
<%= cliq_membership.cliq.name %>
(<%= link_to "Leave Cliq", cliq_membership, :method => :delete %>)
</li>
<% end %>
</ul>
<h3>Title:</h3>
<% @uploads.each do |upload| %>
<div>
<%= link_to upload.title, upload_url %>
</div>
<% end %>
我的遷移:
Cliq手機:
class CreateCliqs < ActiveRecord::Migration
def change
create_table :cliqs do |t|
t.string :name
t.references :owner
t.integer :cliq_id
t.timestamps null: false
end
end
end
個
CliqMemberships:
class CreateCliqMemberships < ActiveRecord::Migration
def change
create_table :cliq_memberships do |t|
t.references :user
t.references :cliq
t.timestamps null: false
end
end
end
什麼BELOW全職工作解決方案。
所以用戶和Cliqs之間有一個橋接表。對於我過去曾經參與過的項目,橋表中有一個「角色」列,表示用戶是管理員,用戶還是組的所有者。這種方法會在這裏工作嗎? – erapert
我將如何去實施呢?我仍然對HMT協會感到困惑。 –
HMT?你的意思是多對多的權利?許多用戶可以屬於很多組,對吧?唯一的限制是用戶只能_own_一個組,對吧? – erapert