How would I destroy a Product if it doesn’t belong to a Store after_save?
class Product < ActiveRecord::Base
attr_accessible :price, :name, :product_store
belongs_to :store
attr_reader :product_store
# I need this to do also "p.product_store.blank?"
after_save { |p| p.destroy if p.name.blank? && p.price.blank? }
def product_store=(id) # using Jquery TokenInput so only needed this.
self.store_id = id
end
end
I’ve tried a couple of different approaches like:
after_save { |p| p.destroy if p.name.blank? && p.price.blank? && p.product_store.blank? }
after_save { |p| p.destroy if p.name.blank? && p.price.blank? && p.store.id.blank? }
after_save { |p| p.destroy if p.name.blank? && p.price.blank? && p.store_id.blank? }
after_save { |p| p.destroy if p.name.blank? && p.price.blank? && p.store.blank? }
But these didn’t work so I ask for your help on how it would be done?
Here is my form and controller: https://gist.github.com/1472629
how about use ActiveModel::Validations?
you don’t want to save record if some attribute not filled.so you need validation.
Edit:
your code looks want to create muti products use common attributes.
may be params like this:
controller
def create_multiple
@products = params[:products].values.collect do |up|
Product.new(up.merge(params[:product]))
end
if @products.each(&:save)
redirect_to :back, :notice => “Success!”
else
render :new
end
end
Validation do not need change. but the form will a bit complicate.
the code is simple, you can enhance the view yourself.