UPDATE麻烦的写入动作
我有我叫set_gold_and_silver
微缩模型的操作。
我希望我的用户模型在用户销毁时运行它,所以我的用户模型中有before_destroy :set_gold_and_silver
。
用户有很多Imagevotes。在销毁之前,我需要删除那些Imagevotes,然后在这些图片投票所涉及的所有缩图上运行set_gold_and_silver
。
这就是我到目前为止,我目前正在undefined method 'miniatures'
。
我不清楚我是否缓存self.imagevotes或者他们是否刚删除,然后我得到的错误,因为他们不再存在?
def set_gold_and_silver
votes = self.imagevotes
self.imagevotes.destroy
votes.miniatures.uniq.each(&:set_gold_and_silver)
end
我的模型
用户
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
has_many :collections, dependent: :destroy
has_many :miniatures, through: :collections
has_many :imagevotes, foreign_key: "voted_id", dependent: :destroy
has_many :imagevotes, foreign_key: "voter_id", dependent: :destroy
before_destroy :set_gold_and_silver
def set_gold_and_silver
my_collections = self.collections.each
their_miniatures = collection.miniature.uniq
my_collections.their_miniatures.each(&:set_gold_and_silver)
end
end
微型
class Miniature < ActiveRecord::Base
has_many :collections, dependent: :destroy
has_many :users, :through => :collections
has_many :imagevotes, dependent: :destroy
def set_gold_and_silver
wipe = self.collections.all
wipe.each {|s| s.update_attributes :is_gold => false, :is_silver => false}
top_collections = self.collections.limit(4)
gold = top_collections.shift
gold.update_attribute :is_gold, true if gold
top_collections.each {|s| s.update_attribute :is_silver, true}
end
end
收藏
class Collection < ActiveRecord::Base
default_scope order('imagevotes_count DESC')
belongs_to :miniature
belongs_to :user
has_many :imagevotes, dependent: :destroy
end
Imagevote
class Imagevote < ActiveRecord::Base
belongs_to :collection, :counter_cache => true
belongs_to :voter, class_name: "User", :counter_cache => "voted_count"
belongs_to :voted, class_name: "User", :counter_cache => "vote_count"
belongs_to :miniature
after_create :set_gold_and_silver
after_update :set_gold_and_silver
def set_gold_and_silver
self.miniature.set_gold_and_silver
end
end
你需要用模型的伪代码更新你的问题用户,微型,集合包括有/属性和过滤器之前/之后。你创建了一个单独的问题是很好的,但即使在那里也是如此,当然也是如此。 –
编辑的问题。 – Ossie