【发布时间】:2017-08-22 16:20:44
【问题描述】:
我正在尝试找到一种方法来清除与另一个表关联的表中的行。
关键是我正在尝试为食谱创建应用程序。 例如,我不想遇到两个或更多食谱具有相同成分(比如说鸡蛋)的情况。如果我删除一个配方,它将自动删除关联的 Active Record,但我想在例如鸡蛋不会在另一个食谱中使用。
成分模型:
class Ingredient < ApplicationRecord
belongs_to :recipe, inverse_of: :ingredients
end
配方模型:
class Recipe < ApplicationRecord
has_many :ingredients, inverse_of: :recipe
has_many :directions, inverse_of: :recipe
accepts_nested_attributes_for :ingredients,
reject_if: proc { |attributes| attributes['name'].blank? },
allow_destroy: true
accepts_nested_attributes_for :directions,
reject_if: proc { |attributes| attributes['step'].blank? },
allow_destroy: true
validates :tittle, :description, :image, presence: true
has_attached_file :image, styles: { :medium => "400x400#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
那么有没有办法(不包括sql查询)来执行这样的操作?
【问题讨论】:
标签: ruby-on-rails associations rails-activerecord