【问题标题】:Issue on association in RAILS关于 RAILS 中关联的问题
【发布时间】:2019-12-18 15:47:40
【问题描述】:

这是我的问题。我有两个模型(建筑和客户)

class Construction < ApplicationRecord
  has_many :works
  belongs_to :customer
end

class Customer < ApplicationRecord
  has_many :constructions
end

我想在创建新结构时将客户与结构相关联。 为此,我必须遵循控制器的方法(这显然是错误的)

def create
  # @construction = Construction.new(constructions_params) (commented)
  @construction = Construction.new(customer: @customer)
  @customer = Customer.find(params[:customer_id])
  @construction.save!
end

从参数中我可以理解,构造没有保存,因为它没有附加到客户,因此无法创建。

我是 Rails 新手,我已经挣扎了好几个小时了..

希望有人能帮助我。

非常感谢

【问题讨论】:

  • params[:construction][:customer_id] 下的 customer_id 可能吗? puts params.inspect 并检查它
  • 显示您的表格。执行puts params.inspect 并显示输出。

标签: ruby-on-rails ruby activerecord rails-activerecord model-associations


【解决方案1】:

尝试恢复订单:

@customer = Customer.find(params[:construction][:customer_id])
@construction = Construction.new(customer: @customer)
@construction.save!

您需要在使用之前分配@customer 实例变量。否则它是 nil 并且没有分配给新的 Construction 记录。

【讨论】:

  • 使用@construction = @customer.constructions.build可能会更好
  • 使用params[:construction][:customer_id](更新代码)
  • 我说得太快了......它正在“工作”创建一个与正确客户相关联的结构,但我无法从我的简单表单中检索所有信息......姓名,地址,音量,持续时间现在设置为零..
  • @BrianRid 请发布一个完整的问题。包括正在提交的参数和预期的结果
  • 好的,我会尝试更具体:以下是以下参数:@construction = @customer.constructions.build(customer: @customer) 参数:“construction”=>{“name "=>"Test", "address"=>"Paris", "duration"=>"12", "volume"=>"12", "customer_id"=>"25"}, "commit"=>" Créer"} 然后保存!是成功的。但我在我的索引上被重定向,我无法找到我新建的建筑。我检查了 rails c --> 除了提交的 customer_id 之外,所有其他的都设置为 nil
【解决方案2】:

如果您在创建表单时有可用的customer_id,我认为您可以这样做。

同样考虑到与构造上的customer 的belongs_to 关系,您应该能够更新构造上的customer_id

def create
  @construction = Construction.new(construction_params)
  if @construction.save
    # whatever you want to do on success
  else
    # Whatever you want to do on failure
  end
end

# Given you have construction params

private

def construction_params
  params.require(:construction).permit(:all, :the, :construction, :attributes, :customer_id)
end

【讨论】:

    猜你喜欢
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多