我有一个非常复杂的关联设置允许我的模型:要评价的东西,我认为通过查看我的模型可以最好地理解。基本上,当创建new:thing时,new:thing_ratings也会根据:属于:thing属于的类别的:rating来创建。
例如,如果a:类别“Books”具有:rating“Plot”,那么使用与Books关联创建的new:thing应该具有:thing_rating也称为“Plot”。
问题是,虽然:thing和:thing_ratings创建没有问题,但在:thing show页面上,我收到此错误:
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly in ThingsController#show
Cannot modify association 'Thing#thing_ratings' because it goes through more than one other association.
如何解决这个问题?我看到了一个类似问题的答案,建议在:thing和:thing_rating readonly之间建立关联,但我也希望能够创建另一个模型的实例:up_votes for:thing_ratings,我不认为我如果关联是只读的,可以做到这一点。
模型/ thing.rb
has_many :category_things
has_many :categories, :through => :category_things
has_many :category_ratings, through: :categories
has_many :ratings, :through => :categories
has_many :thing_ratings, through: :ratings
模型/ category.rb
has_many :category_ratings
has_many :ratings, :through => :category_ratings
has_many :category_things
has_many :things, :through => :category_things
模型/ rating.rb
has_many :category_ratings
has_many :categories, :through => :category_ratings
has_many :thing_ratings
has_many :things, :through => :thing_ratings
模型/ category_thing.rb
belongs_to :category
belongs_to :thing
模型/ category_rating.rb
belongs_to :category
belongs_to :rating
模型/ thing_rating.rb
belongs_to :rating
belongs_to :thing
has_many :up_votes, as: :voteable
控制器/ things_controller.rb
def show
@thing = Thing.find(params[:id])
@thing.categories.build
@category_thing = CategoryThing.all
@category_rating = CategoryRating.all
@thing_ratings = @thing.category_ratings
@thingcats = @thing.categories
@thing.thing_ratings.build
# ...
end
def create
@thing = Thing.new(thing_params)
@category = Category.all
@thing.categories.build
@thing_ratings = @thing.category_ratings
@thingcats = @thing.categories
@thingrats = @thing.ratings
if @thing.save
params["categories"].strip.split(',').map(&:strip).each do |name|
CategoryThing.create!(category_id: Category.where(name: name).first.id, thing_id: @thing.id)
end
@thingrats.each do |r|
ThingRating.create!(rating_id: r.id, thing_id: @thing.id, name: r.name)
end
redirect_to new_thing_path
end
end
答案 0 :(得分:0)
事实证明,我实际上并没有将thing_ratings与评级联系起来。我只是把thing_ratings直接归属于事物。