2016-04-05 46 views
0

我有用戶組。用戶創建一個組,並且是所有者。他們可以接受/拒絕請求(工作正常),創建組(也可以),我希望他們能夠刪除組成員(這是不工作)。出於某種原因,該組的所有者是能夠從該組中刪除的所有內容。如何銷燬has_many:通過選定用戶關聯

如何設置控制器操作/視圖讓所有者刪除組成員?

P.S.我不想爲此使用授權系統。它應該很簡單,只需在控制器中進行即可。我只需要能夠刪除任何組成員。 組= Cliqs。我沒有使會員資格成爲組的嵌套資源。

錯誤:找不到'id'= 2的CliqMembership [哪裏有cliq_memberships。 ?user_id =]

這裏是我的控制器操作:

def destroy 
    @cliq = Cliq.find_by(params[:cliq_id]) 
    @cliq_membership = @cliq.cliq_memberships.find(params[:id]) 

    @cliq_membership.destroy 
    redirect_to cliqs_path 
end 

我的模型:

class Cliq < ActiveRecord::Base 
    belongs_to :owner, class_name: 'User' 

    has_many :cliq_memberships, dependent: :destroy 
    has_many :members, through: :cliq_memberships, source: :user 
end 

class User < ActiveRecord::Base 
    has_one :owned_cliq, foreign_key: 'owner_id', class_name: 'Cliq', dependent: :destroy 

    has_many :cliq_memberships, dependent: :destroy 
    has_many :cliqs, through: :cliq_memberships 
end 

我的視圖控制器動作:

def show 
    @cliq = Cliq.find(params[:id]) 
    @cliq_owner = @cliq.owner 
    @cliq_members = @cliq.members 
    @pending_members = @cliq.pending_members 
    @cliq_requests = @cliq.cliq_requests #(find a way to show all incoming requests) 
    @cliq_memberships = CliqMembership.all 
end 

而我的 「實際」 的觀點:

<div> 
    <% @cliq.members.each do |member| %> 
    <ul><%= link_to member.username, user_path(member) %></ul> 
    <% end %> 
    <% @cliq.cliq_memberships.each do |cliq_membership| %> 
    (<%= link_to "Delete Member", cliq_membership, :method => :delete %>) 
    <% end %> 
</div> 

登錄:

Cliq Load (0.0ms) SELECT `cliqs`.* FROM `cliqs` LIMIT 1 
CliqMembership Load (0.5ms) SELECT `cliq_memberships`.* FROM `cliq_memberships` WHERE `cliq_memberships`.`cliq_id` = 4 AND `cliq_memberships`.`id` = 9 LIMIT 1 
Completed 404 Not Found in 18ms (ActiveRecord: 0.5ms) 

ActiveRecord::RecordNotFound (Couldn't find CliqMembership with 'id'=9 [WHERE `cliq_memberships`.`cliq_id` = ?]): 
app/controllers/cliq_memberships_controller.rb:44:in `destroy' 
+0

當它失敗時,是否有錯誤記錄任何地方?什麼信息?如果您不確定,請嘗試將'destroy'更改爲'destroy!' –

+0

我會更新問題以包含錯誤消息。 –

+0

謝謝,您是否還請添加您的'log/development.log'文件中的位,該文件涵蓋了DELETE請求。 –

回答

0

嘗試改變has_many :cliq_memberships, dependent: :destroyhas_many :cliq_memberships, dependent: :destroy, foreign_key: 'member_id'

+0

我現在不在我的電腦,但我會嘗試。我需要指定class_name還是:source? –

+0

你將不得不檢查模式表壽。我懷疑你在cliq_memberships表中使用的外部id是'member_id'而不是'user_id',這就是爲什麼你會收到錯誤信息 –

0

我解決它通過檢查我的請求的代碼(這也是的has_many:通過聯想和有類似的動作)。不知道爲什麼我花了這麼長時間來解決它。

我改變了我的方法是:

def destroy 
    @cliq = Cliq.find_by(params[:cliq_id]) 
    @cliq_membership = CliqMembership.find(params[:id]) 

    @cliq_membership.destroy 
     flash[:notice] = "You left the Cliq." 
    redirect_to cliqs_path 
end 
相關問題