【发布时间】:2014-11-18 16:15:14
【问题描述】:
大家好,我开始在 Rails 应用程序中工作。 我对关联有疑问,我有这个: 一个表User,一个表Task和一个表Type,表之间的关系是: 一个用户有很多任务,任务有一个特定的类型。
在我的控制器 user_controller.rb 中,当我要创建一个新任务时,我有以下内容:
def create
@task = Task.new(task_params) #Working
@user = User.find(5) #this is for a while
@type = Type.find(params[:type_id]) #Working
@task = @type.tasks.create(task_params) #this line saves the Task with the asociated Type
@task = @user.tasks.create(task_params) #this line saves the Task with the asociated User
#But the two lines together doesn't work
#Con las validaciones puestan en el model se debe validar el retorno del metodo save
if @task.save
redirect_to @task
else
render 'new'
end
end
编辑:这两行不能一起工作,因为只保存与用户的关联(第二行)可能是因为第二行使用最近的@user.task.create(...) 调用保存方法,如果第二行行被注释,然后第一行只保存类型关联(显然)。我想保存 2 个关联,而不是其中之一 :)
任务模型
class Task < ActiveRecord::Base
belongs_to :type
belongs_to :user
end
类型模型
class Type < ActiveRecord::Base
has_many :tasks, dependent: :destroy
validates :nombre, presence: true, length: { minimum: 3 }
validates :desc, presence: true
end
用户模型
class User < ActiveRecord::Base
belongs_to :perfil
has_many :tasks, dependent: :destroy
end
如何正确保存包含用户和关联类型的任务?谢谢!
【问题讨论】:
-
请解释“但是这两行一起不起作用”
标签: ruby-on-rails activerecord