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

时间:2016-02-23 09:45:53

标签: ruby-on-rails ruby

有两种型号TaskProjectProject有许多任务和一个'任务' belongs_to a'Project'。

class Task < ActiveRecord::Base
  belongs_to :project
end

class Project < ActiveRecord::Base
  has_many :tasks
end

所有Task的列表会显示为每个Project的单独页面,并显示您的Task

如何为方法create创建条件,以便Task能够创建为独立对象,并与Project相关联?

我的知识只够写两种不同的方法。

创建关联对象:

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

创建单独的对象:

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

如何做一个方法?

2 个答案:

答案 0 :(得分:1)

您必须将project_id传递给第二种方法。然后你可以添加

@task.project_id = params[:project_id]

或类似的东西。如果任务始终属于项目,您可能希望将它们建模为nested resource

答案 1 :(得分:0)

任务控制器:

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
 ...

项目模型:

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

和项目控制器

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