ruby-on-rails - Rails API 嵌套属性 Find_or_create 以避免重复不起作用
问题描述
我试图在重复的情况下控制嵌套属性,找到该行并使用它而不是创建一个新行,它可以在较低的嵌套级别(即餐点)上正常工作。
但是,如果我使用它,plan.rb 中的注释代码(您可以在下面查看)会使饭菜变为空白,就好像我没有在我的请求中传递任何饭菜一样,对此有什么想法吗?
计划.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
日.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
膳食.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
很抱歉让这么长,但我想提供尽可能多的细节。
解决方案
由于您正在映射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
推荐阅读
- angular - 我有一个角度服务,我在那个服务中有静态方法。如何为静态方法编写单元测试?
- python - “内部连接”就像在 Flask、Jinja 中使用 MongoDB
- apache-kafka - 卡夫卡生产者与卡夫卡连接器
- ruby-on-rails - 覆盖 Rails 模型中的验证
- scala - 如何使用 net.ruippeixotog.scalascraper 从列表中抓取所有文本
- javascript - ember js中push和pushObject的区别
- python - 三元运算符的替代实现,一个衬里
- javascript - 如何从 Google Sheet 获取日期类型的 HTML 元素?
- liquibase - 有没有办法在运行时使用 Liquibase 将属性替换作为参数传递?请分享一个例子?
- python - python中的API请求和“进程以退出代码0完成”