未定義のメソッドに関する仮想属性の問題
-
07-07-2019 - |
質問
過去に仮想属性を使用したことがありますが、これを乗り越えることはできないようです。おそらく、答えが顔を凝視していることを知っています。
次のようなモデルがあります:
model Confirmation.rb
class Confirmation < ActiveRecord::Base
#attr_accessible :confirmation, :confirmation_token
#attr_accessible :confirmation_token
def confirmation_token
confirmation.confirmation_token if confirmation
end
def confirmation_token=(token)
self.confirmation = Booking.find_by_confirmation_token(token)
end
end
平均的な足場コントローラー
confirmations_controller.rb
def new
@confirmation = Confirmation.new(:confirmation_token => params[:confirmation_token])
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @confirmation }
end
end
new.html.erb
<h1>New confirmation</h1>
<% form_for(@confirmation) do |f| %>
<%= f.error_messages %>
<%= f.hidden_field :confirmation_token %>
...
routes.rb
map.confirmation "confirmation/:confirmation_token", :controller => "confirmations", :action => "new"
map.resources :confirmations
エラー
#の未定義メソッド「confirmation =」
コンソールでは、所定のトークンを使用したBooking.find_by_confirmation_token(token)は完全に機能します。
アイデアはありますか?提案?
解決
次のいずれかにすべきだと思います:
def confirmation_token=(token)
@confirmation = Booking.find_by_confirmation_token(token)
end
または、 attr_accessible:confirmation
のコメントを解除するか、 #confirmation
および #confirmation =
を定義する必要があります。
他のヒント
本当に必要なのはattr_accessor:confirmationです。 attr_accessibleとattr_accessorには違いがあります。
attr_accessor :confirmation
と同じ
def confirmation
@confirmation
end
def confirmation=(value)
@confirmation = value
end
今ではそのような一般的なパターンなので、ルビーはそのためのヘルパーメソッドを導入しました。
一方、Attr_accesibleはrailsメソッドで、特定のフィールドを一括更新できることを示します。class Confirmation < ActiveRecord::Base
belongs_to :bookings
#attr_accessible :confirmation, :confirmation_token
#attr_accessible :confirmation
def confirmation_token
@confirmation.confirmation_token if @confirmation
end
def confirmation_token=(token)
@confirmation = Booking.find_by_confirmation_token(token)
end
end
これは機能しました...しかし、attr_accessible:confirmationを発見しただけでは、そうではありませんでした。 self.confirmationは未定義のメソッドを返しました...
所属していません StackOverflow