【问题标题】:How to save associations with ActiveRecord Ruby On Rails如何保存与 ActiveRecord Ruby On Rails 的关联
【发布时间】: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


【解决方案1】:

调用tasks.create(task_params) 你实际上是在为类型和用户创建一个新任务。相反,您只想像这样设置关联:

def create
  @task = Task.new(task_params)
  @user = User.find(5)
  @type = Type.find(params[:type_id])
  @task.user = @user # Just set the reference!
  @task.type = @type # Just set the reference!

  if @task.save
    redirect_to @task
  else
    render 'new'
  end
end

【讨论】:

    【解决方案2】:

    由于 User 和 Type 都具有关系 'has_many :tasks',因此它们每个都有一个与之关联的 tasks[] 数组。在这种情况下,您可以执行以下操作:

    def create
      @task = Task.new(task_params)
      @user = User.find(5)
      @type = Type.find(params[:type_id])
      @type.tasks << @task
      @user.tasks << @task
    
      if @user.save && @type.save
        redirect_to @task
      else
        render 'new'
      end
    end
    

    保存@user 和@type 将自动保存与其关联的任务,如果它们尚未保存的话。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多