我试图将一个对象保存到数据库中,并创建has_many关联,但它失败了验证。我目前正在使用Postgres的Rails 5.2上。
item.rb
class Item < ApplicationRecord
has_many :routings, dependent: :destroy
has_many :work_centers, through: :routings
validates :number, presence: true,
length: { maximum: 255 },
uniqueness: true
...
endrouting.rb
class Routing < ApplicationRecord
belongs_to :item
belongs_to :work_center
validates :item_id, presence: true
validates :work_center_id, presence: true
...
endwork_center.rb
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
enditems_controller.rb
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时,它会失败,出现验证错误:
> Item.create!(job_id: 58, number: "6872-ryan1", work_center_ids: [3,4])
ActiveRecord::RecordInvalid: Validation failed: Routings is invalid但是,如果我先创建Item,然后添加Routings,它就成功了:
> 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
class Item < ApplicationRecord
has_many :routings, dependent: :destroy
has_many :work_centers, through: :routings, inverse_of: :item
...
end更新work_center.rb
class WorkCenter < ApplicationRecord
has_many :routings, dependent: :destroy
has_many :items, through: :routings, inverse_of: :work_center
end但现在我得到了一个不同的错误:
> 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)编辑以显示模型中的有效性
发布于 2019-01-10 18:43:24
从ROR的第5个版本开始,默认情况下将验证belongs_to关联,因此在路由模型中不需要这些行:
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列是否有某些值。
https://stackoverflow.com/questions/54131016
复制相似问题