【问题标题】:Rails API nested attirbutes Find_or_create to avoid duplications doesn't workRails API 嵌套属性 Find_or_create 以避免重复不起作用
【发布时间】:2021-10-05 04:00:24
【问题描述】:

我正在尝试控制嵌套属性以防出现重复,请务必找到该行并使用它而不是创建一个新行,它可以在较低的嵌套级别(即餐点)上正常工作。

但是,如果我使用它,plan.rb 中的注释代码(您可以在下面查看)会使餐点空白,就好像我没有在我的请求中传递任何餐点,对此有什么想法吗?

Plan.rb

class Plan < ApplicationRecord
  has_and_belongs_to_many :meals
  has_and_belongs_to_many :days
  has_one_attached :image, dependent: :destroy
  validate :acceptable_image
  accepts_nested_attributes_for :days, reject_if: ->(object) { object[:number].blank? }

  #! this is causing meals to not save
  # # before_validation :find_days
  # def find_days
  #   self.days = self.days.map do |object|
  #     Day.where(number: object.number).first_or_initialize
  #   end
  # end
  #!
end

Day.rb

class Day < ApplicationRecord
  has_and_belongs_to_many :meals
  has_and_belongs_to_many :plans
  accepts_nested_attributes_for :meals, reject_if: ->(object) { object[:name].blank? }
  before_validation :find_meals

  def find_meals
    self.meals = self.meals.map do |object|
      Meal.where(name: object.name).first_or_initialize
    end
  end
end

Meal.rb

class Meal < ApplicationRecord
  has_and_belongs_to_many :plans
  has_and_belongs_to_many :days
end

这就是我允许我的参数的方式

def plan_params
    params.require(:plan).permit(:name, :monthly_price, :image_url, days_attributes: [:number, meals_attributes: [:name, :calories, :protein, :fat, :carbohydrates, :categorie]])
end

很抱歉拖这么久,但我想提供尽可能多的细节。

【问题讨论】:

    标签: ruby-on-rails ruby api nested associations


    【解决方案1】:

    由于您正在映射 self.days 关联,Day.where(number: object.number).first_or_initialize 将 days 数组替换为 Day 对象,而没有任何 meal 属性。

    您需要在 map 块内执行类似的操作:

    day = Day.where(number: object.number).first_or_initialize
    day.attributes = object.attributes
    # or similar, to copy the nested attributes provided by the request 
    
    day 
    

    【讨论】:

    • 你能解释一下你的例子吗,或者你能给我更多的细节吗?
    猜你喜欢
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多