0

我有一個項目模型和一個任務模型,但是任務可以有很多項目,反之亦然......所以我創建了一個關係兩者之間的模型。現在從項目配置文件中,我希望能夠創建一個任務並自動讓它創建任務以及新任務與創建項目之間的關係。在嘗試從項目配置文件創建任務時找不到項目'id'=

但是當我試圖做到這一點我收到以下錯誤:

ActiveRecord::RecordNotFound in TasksController#create 
Couldn't find Project with 'id'= 

用戶是項目展示頁面上點擊一個鏈接到「提交新任務」。我意識到我沒有通過項目ID以某種方式,但我似乎無法弄清楚如何做到這一點,因爲我使用TaskRelationship模型來關聯任務和項目(我沒有在項目中嵌套任務在我的路線)。

的意見/項目/ show.html.erb:

<%= link_to "+ Submit New Task", new_task_path, :class => "btn btn-info col-md-12" %> 

在新的任務視圖,我需要創建兩個任務,任務和項目之間的關係。

的意見/任務/ new.html.erb:

<div class="container sign-in-register"> 
    <div class="authform"> 

      <%= form_for @task, :html => {:multipart => true} do |f| %> 

      <h3>Submit new task to this project...</h3><br/> 

      <%= render 'shared/error_messages', object: f.object %> 

      <%= f.label :Title %> 
      <%= f.text_field :title, class: 'form-control' %> 

      <%= f.label :Description %> 
      <%= f.text_area :description, class: 'form-control' %> 

      <br clear="all"> 

      <%= f.submit "Add this Task", class: "btn btn btn-info" %> 
      <% end %> 

    </div> 
</div> 

TaskRelationship模型(鏈接任務項目):

class TaskRelationship < ActiveRecord::Base 
    belongs_to :taskproject, class_name: "Project" 
    belongs_to :projecttask, class_name: "Task" 
    validates :taskproject_id, presence: true 
    validates :projecttask_id, presence: true 
end 

項目型號:

class Project < ActiveRecord::Base 
    belongs_to :owner, :foreign_key=>'user_id', :class_name=>'User' 

    has_many :tasks 
    has_many :taskrelationships, foreign_key: "taskproject_id", dependent: :destroy 
    has_many :projecttasks, through: :taskrelationships, source: :projecttask 

    validates :title, presence: true 
    validates :background, presence: true 

    def related?(some_task) 
    taskrelationships.find_by_projecttask_id(some_task.id) 
    end 

    def relate!(some_task) 
    self.taskrelationships.create!(projecttask_id: some_task.id) 
    end 

end 

任務型號:

class Task < ActiveRecord::Base 
    belongs_to :owner, :foreign_key=>'user_id', :class_name=>'User' 

    has_many :projects 
    has_many :reverse_taskrelationships, foreign_key: "projecttask_id", 
            class_name: "TaskRelationship", 
            dependent: :destroy 
    has_many :taskprojects, through: :reverse_taskrelationships, source: :taskproject 

    validates :title, presence: true 
    validates :description, presence: true, length: { maximum: 140 } 
end 

任務控制器:

class TasksController < ApplicationController 

    def new 
    @task = Task.new 
    end 

    def create 
    @project = Project.find(params[:taskproject_id]) 
    @task = current_user.own_tasks.build(task_params) 
    if @task.save 
     flash[:success] = "Your task has been created." 
     redirect_to @task 
     @project.relate!(@task) unless @project.related?(@task) # establish task relationship w/ project only if doesn't exist 
    else 
     render 'task' 
    end 
    end 

private 

def task_params 
     params.require(:task).permit(:title, :description, :user_id, task_relationship_attributes: [:taskproject_id, :projecttask_id]) 
end 

end 

Task_Relationships_Controller:

class TaskRelationshipsController < ApplicationController 
    before_filter :authenticate_user! 

    def create 
    end 

    def destroy 
    end 

    # I assume (maybe incorrectly) that i don't need create/destroy actions but do need strong params 

    private 

    def task_relationship_params 
    params.require(:taskrelationship).permit(:taskproject_id, :projecttask_id) 
    end 
end 

我怎樣才能獲得通過,以使新任務創造了這個正確的ID和任務與項目之間的新taskRelationship? THX,

UPDATE:

嘗試後,當我已經添加了日誌詳細

終端日誌:

Started GET "/tasks/new" for ::1 at 2016-04-15 19:55:54 -0500 
Started GET "/tasks/new" for ::1 at 2016-04-15 19:55:54 -0500 
Processing by TasksController#new as HTML 
Processing by TasksController#new as HTML 
    Rendered shared/_error_messages.html.erb (0.1ms) 
    Rendered shared/_error_messages.html.erb (0.1ms) 
    Rendered tasks/new.html.erb within layouts/application (24.5ms) 
    Rendered tasks/new.html.erb within layouts/application (24.5ms) 
    Rendered layouts/_shim.html.erb (0.0ms) 
    Rendered layouts/_shim.html.erb (0.0ms) 
    User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 4]] 
    User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 4]] 
    Rendered layouts/_navigation_links.html.erb (1.6ms) 
    Rendered layouts/_navigation_links.html.erb (1.6ms) 
    Rendered layouts/_header.html.erb (2.9ms) 
    Rendered layouts/_header.html.erb (2.9ms) 
    Rendered layouts/_footer.html.erb (0.0ms) 
    Rendered layouts/_footer.html.erb (0.0ms) 
Completed 200 OK in 192ms (Views: 185.6ms | ActiveRecord: 1.0ms) 
Completed 200 OK in 192ms (Views: 185.6ms | ActiveRecord: 1.0ms) 




Started POST "/tasks" for ::1 at 2016-04-15 19:55:59 -0500 
Started POST "/tasks" for ::1 at 2016-04-15 19:55:59 -0500 
Processing by TasksController#create as HTML 
Processing by TasksController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"DGGG+zWPMbB7OwZz8oCVLB5O6sMfTe/Orj6KfeP6mrveOH0ImAP4aow0gufqefOdwsp8v4GDEt8ppJiL4CvQVg==", "task"=>{"title"=>"test", "description"=>"test"}, "commit"=>"Add this Evidence"} 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"DGGG+zWPMbB7OwZz8oCVLB5O6sMfTe/Orj6KfeP6mrveOH0ImAP4aow0gufqefOdwsp8v4GDEt8ppJiL4CvQVg==", "task"=>{"title"=>"test", "description"=>"test"}, "commit"=>"Add this Evidence"} 
    Project Load (0.3ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1 [["id", nil]] 
    Project Load (0.3ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT 1 [["id", nil]] 
Completed 404 Not Found in 2ms (ActiveRecord: 0.3ms) 
Completed 404 Not Found in 2ms (ActiveRecord: 0.3ms) 

ActiveRecord::RecordNotFound (Couldn't find Project with 'id'=): 
    app/controllers/tasks_controller.rb:8:in `create' 

ActiveRecord::RecordNotFound (Couldn't find Project with 'id'=): 
    app/controllers/tasks_controller.rb:8:in `create' 

回答

3

1)您需要以某種方式將項目ID傳遞給TasksController#new。 一種方法是把它作爲請求URL的一部分,是這樣的:

<host>/tasks/new?project_id=<project ID> 

這將使它在請求的params變量可用。

2)在您的TasksController#新動作中,將project_idparams傳遞到視圖。最簡單的方法是使用一個實例變量:

@project_id = params[:project_id] 

有隻傳一個對象的觀點,在這裏我們傳遞2理念:@task和@project_id。我不擔心它,但你可能想要閱讀表單對象:https://robots.thoughtbot.com/activemodel-form-objects

3)在窗體上添加一個隱藏的字段與項目ID。因爲@project_id不是@task模型的一部分,我們將使用的輸入標籤幫手,而不是基於表單的助手:

<%= hidden_field_tag 'project_id', @project_id %> 

API文檔:http://apidock.com/rails/ActionView/Helpers/FormTagHelper/hidden_field_tag

現在的@project_id值將是傳遞給#create行動params[:project_id]當用戶點擊按鈕submit

4)變更PARAMS在TasksController#create行動。 project_id將嵌套在與task參數:

@project = Project.find(PARAMS [:PROJECT_ID])

5)你需要創建TaskRelationship關係。有幾種方法可以做到這一點。我通常使用build

@task.taskprojects.build(project: @project) 

所以你#create行動看起來是這樣的:

@project = Project.find(params[:project_id]) 
@task = current_user.own_tasks.build(task_params) 
@task.taskprojects.build(project: @project) 
if @task.save 
... 
+0

THX阿蘭 - 我覺得我最以下這只是第一步。我在哪裏完成在URL中傳遞它?它會在新任務操作的路線中嗎? (在這種情況下,任務確實屬於多個項目,所以我可能無法採用belongs_to方法)。 – BB500

+0

無視阿蘭 - 我剛剛通過了(:PROJECT_ID => @ project.id)在new_task_path結束。 – BB500

+0

我遵循了所有步驟...... 1)工作得很好。但2)引起一個問題:試圖訪問新任務頁面時,我現在得到TasksController#新 未定義的方法'PROJECT_ID =」 NoMethodError爲無:NilClass – BB500

1

在你的控制器聲明Project.find(params[:taskproject_id]),它看起來像params[:taskproject_id]是零。查看錶單視圖中的代碼,傳遞給控制器​​的參數應爲params[:id]。目前還不清楚task_params在哪裏定義

如果您仍然收到錯誤,請檢查您提交表單並將它們發佈到此處時的日誌輸出中的參數。

+0

THX安東尼 - 我已經添加了我的任務參數Code(在任務控制器的底部)。如何/應該在哪裏傳遞你提到的params [:id]? – BB500

+0

在你的'TasksController#create'聲明,我已經更新了我的答案。 –

+0

它仍然沒有找到該ID ......我顯然沒有正確傳遞它。我已更新日誌輸出。 – BB500

相關問題