简体   繁体   English

Rails:使用has_many / Emirates_to关联创建对象

[英]Rails: Object creation with has_many / belongs_to association

There are two models Task and Project . TaskProject两个模型。 A Project has many 'Task's and a 'Task' belongs_to a `Project'. 一个Project有许多“任务”,一个“任务”属于一个“项目”。

class Task < ActiveRecord::Base
  belongs_to :project
end

class Project < ActiveRecord::Base
  has_many :tasks
end

A list of all Task s is displayed as a separate page for each Project and displays your Task s. 所有Task的列表显示为每个Project的单独页面,并显示您的Task

How to create the condition for the method create , so that the Task be able to be created as an independent object, and associated with the Project ? 如何为create方法create条件,以便能够将Task创建为独立对象并与Project关联?

My knowledge was only enough to write two separate methods. 我的知识仅足以编写两种不同的方法。

To create associated objects: 创建关联对象:

def create
  @project = Project.find(params[:project_id])
  @task = @project.tasks.create(task_params)
  redirect_to project_path(@project)
end

To create a separate object: 要创建一个单独的对象:

def create
  @task = current_user.tasks.new(task_params)

  respond_to do |format|
    if @task.save
      format.html { redirect_to @task, notice: 'Task was successfully created.' }
      format.js {}
      format.json { render json: @task, status: :created, location: @task }
    else
      format.html { render action: "new" }
      format.json { render json: @task.errors, status: :unprocessable_entity }
    end
  end
end

How to do it one method? 一种方法怎么办?

You have to pass in the project_id to your second method. 您必须将project_id传递给第二种方法。 Then you can add 然后您可以添加

@task.project_id = params[:project_id]

or something like that. 或类似的东西。 If tasks always belongs to projects you may want to model them as a nested resource . 如果任务始终属于项目,则可能需要将它们建模为嵌套资源

Task Controller: 任务控制器:

def index
  @tasks = Task.all
  @task  = Task.new
end

def create
 @task = if params[:project_id]
   @project = Project.find(params[:project_id])
   @project.tasks.build(task_params)
 else
   Task.new(task_params)
 end
 ...

Project Model: 项目模型:

class Project < ActiveRecord::Base
  has_many :tasks, dependent: :destroy
  accepts_nested_attributes_for :tasks,
                      :allow_destroy => true
end

and in projects controller 和项目负责人

private      
def project_params
      params.require(:project).permit(:name, ....., taks_attributes: [:id, .....,:_destroy])
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM