i have been banging my head against the wall for the past few hours with this problem, i can't seem to figure out myself. Okay i have two models that look like this
class Book < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :books
end
Categories have many books and book have several categories. And what i want to do is to create this thing that will point at book who is the best in that category. For example:
Da vinci code <- Drama <- Best(Drama)
Lord of the Rings <- Fantasy <- Best(Fantasy)
Hobbit <- Fantasy
Twilight <- Stupidity <- Best(Stupidity)
But i cant quite grasp how can i accomplish this. In form for this Best option i have checkbox, and for categories i have dropdown with multiselect. And if there is several categories selected and Best checked than what i want, is if there was another Best book than this book now becomes "not" the best book, and the newly checked and saved becomes Best!
I figured out a workaround for now, but it does not seem "Raily" for me. Workaround is to add Best column for Categories with Book id and use after_save callback. something like this:
def best_book
if self.best
Category.where(id: self.category_ids).update_all(default: self.id)
Category.where.not(id: self.category_ids, best: self.id).update_all(best: nil)
else
Category.where(best: self.id).update_all(best: nil)
end
end