如何将user_id传递给nested_resource模型?

时间:2012-01-19 20:27:04

标签: ruby-on-rails-3.1 devise cancan formtastic nested-resources

我有一个使用设计和cancan的小型项目设置。有用户,项目,责任和任务模型。 Project已嵌套任务。每个项目都分配给一个或多个用户。任务模型有一个名称user_id和project_id。身份验证和授权正如预期的那样工作。

当添加一个新的Task(只有一个name的输入)时,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
  ...

1 个答案:

答案 0 :(得分: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

不确定这是不是你的意思