我有一个带有 devise 和 cancan 的小项目设置。有用户模型、项目模型、责任模型和任务模型。项目有嵌套任务。每个项目都分配给一个或多个用户。任务模型具有名称、user_id 和 project_id。身份验证和授权按预期工作。
添加新任务(仅输入名称)时,project_id 会自动传递给模型/表(我认为这是因为路由),而不是 user_id。
我是否必须在 hidden_field 中传递 user_id 或者是否可以在过滤器之前设置它?
有人可以提示如何在任务控制器中设置 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
...