1

我有一個設計和康康的小項目設置。有用戶,項目,負責任和任務模型。項目嵌套了任務。每個項目分配給一個或多個用戶。任務模型具有名稱user_id和project_id。身份驗證和授權正在按預期工作。如何將user_id傳遞給nested_resource模型?

當添加一個新的任務(只有名稱輸入)時,project_id會自動傳遞給model/table(我認爲這是因爲路由),但不是user_id。

我是否必須在hidden_​​field中傳遞user_id或者是否可以在過濾器中設置此項?

有人可以給一個關於如何在taskcontroller中設置user_id的提示嗎?

感謝

# Routes 

resources :projects do 
    resources :tasks 
end 

#Models 

class User < ActiveRecord::Base 
    has_many :responsibilities, :dependent => :destroy 
    has_many :projects, :through => :responsibilities 
    has_many :tasks, :dependent => :destroy 
... 

class Project < ActiveRecord::Base 
    has_many :tasks, :dependent => :destroy 
... 

class Task < ActiveRecord::Base 
    belongs_to :project 
    belongs_to :user 
... 

# Tasks Controller with all Task.find/new/update/... 
# methods removed like explained in cancan manual 

class TasksController < ApplicationController 
    load_and_authorize_resource :project 
    load_and_authorize_resource :task, :through => :project 
    ... 
    def create 
    respond_to do |format| 
     if @task.save 
     format.html { redirect_to [@project, @task], notice: 'created.' } 
     else 
     format.html { render action: "new" } 
     end 
    end 

# Task Form View 
<%= semantic_form_for [@project, @task] do |f| %> 
    <%= f.inputs do %> 
    <%= f.input :name %> 
    <% end %> 
    <%= f.actions %> 
<% end %> 

更新

看來濾波器之前有工作。這是正確的方式嗎?

class TasksController < ApplicationController 
    before_filter :set_user, :only => [:create] 
    load_and_authorize_resource :client 
    load_and_authorize_resource :task, :through => :client, :shallow => true 
    ... 
    def set_user() 
    params[:task][:user_id] = current_user.id.to_s 
    end 
    ... 

回答

0

如果您使用的設計,你可以只通過在創建操作你user_id說明

def create 
    @task.user = current_user 
    respond_to do |format| 
     if @task.save 
     format.html { redirect_to [@project, @task], notice: 'created.' } 
     else 
     format.html { render action: "new" } 
     end 
    end 

靜不知道如果這是你的意思