Rails如何创建一个独立的对象

时间:2016-03-03 08:30:51

标签: ruby-on-rails

两个对象TaskProject有关联has_many - belongs_to

class Project < ActiveRecord::Base
  has_many :tasks, dependent: :destroy
end

class Task < ActiveRecord::Base
  belongs_to :project
end

任务控制器,创建关联对象的方法:

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

    respond_to do |format|
      if @task.save
        format.html { redirect_to @project, 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

查看任务#index,其中包含所有任务的列表。任务控制器方法索引:

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

如何在此方法中创建独立对象Task

错误:

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

我可以创建另一种方法create并使用它吗?

2 个答案:

答案 0 :(得分:3)

将以下行添加到项目模型中。

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

答案 1 :(得分:1)

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