のために作成します。私はstate
のための新しいオブジェクトを作成するときNoMethodErrorは、私は次のようしているRailsの3.1を使用して未定義のメソッド `update_column」
# state.rb
class State < ActiveRecord::Base
belongs_to :country, :touch => true
after_save :count_total_states
private
def count_total_states
total_states = State.where(:country_id => self.country_id).count
Country.where(:id => self.country_id).update_column(:state, total_states)
end
end
# states_controller.rb
class StatesController < ApplicationController
def create
@country = Country.find(params[:country_id])
@state = @country.states.build(params[:state])
@state.position = State.where(:country_id => @country.id).maximum(:position).to_i + 1
@state.save
end
end
、次のエラーが表示さ:
NoMethodError in StatesController#create
undefined method `update_column' for #<ActiveRecord::Relation:0x1074b0e58>
コントローラに戻る方法は?お知らせ下さい。
ありがとうございました。
Country.where(:id => self.country_id)
ActiveRecord::Relation
オブジェクトではなく、国を返します。これはので
感謝。私はオブジェクトを返すべきだと思った? 「国ではない」とはどういう意味ですか?とにかく、ユーザーに動的に状態を追加/削除させるので、私は 'カウンタキャッシュ 'を使うことができません。 – Victor
これはオブジェクトを返します。ルビのすべてがオブジェクトです。カントリオブジェクトの代わりにActiveRecord :: Relationオブジェクトを返すだけです。カウンタキャッシュは、ユーザーがページ/ dbと動的にやりとりすることで動作します。私は常にアプリケーションで使用します。 railscastとブログ記事をチェックしてください。これは、Code SchoolコースのRailsベストプラクティスでもカバーされています。 – Andrew