首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用has_many关联保存模型失败验证

使用has_many关联保存模型失败验证
EN

Stack Overflow用户
提问于 2019-01-10 14:40:14
回答 1查看 1.1K关注 0票数 1

我试图将一个对象保存到数据库中,并创建has_many关联,但它失败了验证。我目前正在使用Postgres的Rails 5.2上。

item.rb

代码语言:javascript
复制
class Item < ApplicationRecord
  has_many :routings,     dependent: :destroy
  has_many :work_centers, through: :routings
  validates :number, presence: true, 
                     length: { maximum: 255 },
                     uniqueness: true
  ...
end

routing.rb

代码语言:javascript
复制
class Routing < ApplicationRecord
  belongs_to :item
  belongs_to :work_center
  validates :item_id, presence: true
  validates :work_center_id, presence: true
  ...
end

work_center.rb

代码语言:javascript
复制
class WorkCenter < ApplicationRecord
  has_many :routings, dependent: :destroy
  has_many :items,    through: :routings
  validates :name, presence: true, length: { maximum: 255 }, 
                   uniqueness: { case_sensitive: false }
  validates :sequence, presence: true,
                       uniqueness: true
end

items_controller.rb

代码语言:javascript
复制
def create
  @item = Item.new(item_params)
  if @item.save
    ...
  end
end

private
  def item_params
    params.require(:item).permit(:job_id, :number, :product_type, work_center_ids: [])
  end

当我试图在rails控制台中创建一个新的Item时,它会失败,出现验证错误:

代码语言:javascript
复制
>   Item.create!(job_id: 58, number: "6872-ryan1", work_center_ids: [3,4])
ActiveRecord::RecordInvalid: Validation failed: Routings is invalid

但是,如果我先创建Item,然后添加Routings,它就成功了:

代码语言:javascript
复制
>   i = Item.create!(job_id: 58, number: "6872-ryan1")
 => #<Item id: 583, number: "6872-ryan1", product_type: nil, job_id: 58, created_at: "2019-01-10 14:28:16", updated_at: "2019-01-10 14:28:16">
>   i.work_center_ids = [3,4]
 => [3, 4]

我尝试将inverse_of:添加到模型中:

更新item.rb

代码语言:javascript
复制
class Item < ApplicationRecord
  has_many :routings,     dependent: :destroy
  has_many :work_centers, through: :routings, inverse_of: :item
  ...
end

更新work_center.rb

代码语言:javascript
复制
class WorkCenter < ApplicationRecord
  has_many :routings, dependent: :destroy
  has_many :items,    through: :routings, inverse_of: :work_center
end

但现在我得到了一个不同的错误:

代码语言:javascript
复制
> Item.create!(job_id: 58, number: "6872-ryan2", work_center_ids: [3])
ActiveRecord::InverseOfAssociationNotFoundError: Could not find the inverse association for work_centers (:item in WorkCenter)

编辑以显示模型中的有效性

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-10 18:43:24

从ROR的第5个版本开始,默认情况下将验证belongs_to关联,因此在路由模型中不需要这些行:

代码语言:javascript
复制
validates :item_id, presence: true
validates :work_center_id, presence: true

如果删除后可以在没有item_id或work_center_id的情况下创建路由,请在配置文件中将belongs_to_required_by_default = false更改为true

无论如何,您应该验证关联模型的存在,而不是它的id。在前一种情况下,您可以在db中使用给定的id检查条目(例如),而在后一种情况下,只需检查item_id列是否有某些值。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54131016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档