我正在尝试增加列并在创建项目时更新属性:
def items_create
@categories = Category.all
@item = Item.new(item_params)
@item.store_id = current_store.id
@item.update(account_id: current_store.account.id)
@search_suggestion = SearchSuggestion.where(term: [@item.title])
@search_suggestion.update_attributes(:items_count => +1 )
respond_to do |format|
if @item.save
format.html { redirect_to store_items_index_path(current_store), notice: 'Item was successfully created.' }
format.json { render :template => "stores/items/show", status: :created, location: @item }
else
format.html { render :template => "stores/items/new" }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end
我找到了对象:
CACHE SearchSuggestion Load (0.0ms) SELECT "search_suggestions".* FROM "search_suggestions" WHERE "search_suggestions"."term" = 'Rolex' LIMIT $1 [["LIMIT", 11]]
但是我收到了这个错误:
NoMethodError (undefined method `update_attributes' for #<ActiveRecord::Relation []>
Did you mean? update_all):
任何想法我可能做错了什么?
答案 0 :(得分:3)
where
返回集合。使用find
或@search_suggestion.last.update_attributes
@search_suggestion = SearchSuggestion.find_by(term: @item.title.downcase)
if @search_suggestion.present?
@search_suggestion.increment!(:items_count)
end
答案 1 :(得分:2)
返回对象集合的位置。要更新对象,我们需要object.So
的实例@search_suggestion = SearchSuggestion.find_or_creat_by_term(@item.title)
update_attributes适用于对象的实例。此外,您还可以使用update_attribute:
@search_suggestion.update_attribute(:items_count, @search_suggestion.items_count +=1 ) if @search_suggestion.exist?
答案 2 :(得分:0)
增加你可以尝试这个
@search_suggestion.increment!(:items_count)
所以代码看起来像
def items_create
@categories = Category.all
@item = Item.new(item_params)
@item.store_id = current_store.id
@item.save!
@item.update(account_id: current_store.account.id)
@search_suggestion = SearchSuggestion.find_by_term(@item.title)
@search_suggestion.increment!(:items_count) if @search_suggestion.present?
respond_to do |format|
if @item.save
format.html { redirect_to store_items_index_path(current_store), notice: 'Item was successfully created.' }
format.json { render :template => "stores/items/show", status: :created, location: @item }
else
format.html { render :template => "stores/items/new" }
format.json { render json: @item.errors, status: :unprocessable_entity }
end
end
end