2009-09-16 54 views
0

我已經使用了過去的虛擬屬性,但我似乎無法超越這一點,而且我知道答案可能正在盯着我。未定義方法的虛擬屬性問題

我有一個模型,如下所示:

模型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 

誤差

未定義的方法`確認=」爲#

在控制檯Booking.find_by_confirmation_token(令牌)與給定的令牌工作完全正常。

任何想法?建議?

回答

2

我認爲它應該是:

def confirmation_token=(token) 
    @confirmation = Booking.find_by_confirmation_token(token) 
end 

還是應該取消註釋attr_accessible :confirmation或定義#confirmation#confirmation=

+0

這很奇怪。我在@之前嘗試過同樣的事情,而不是自己......並且它不起作用。但是這一次呢。仍然不知道什麼改變了..謝謝。 – holden 2009-09-16 10:40:50

0
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:確認,沒有。 self.confirmation仍然返回undefined方法...

+0

我還想知道爲什麼? – holden 2009-09-16 10:43:48

+2

attr_accessible僅用於通過Model#屬性進行質量分配。它沒有定義getters/setters。 attr_accessor正在這樣做。 – Koraktor 2009-09-16 10:53:28

+0

啊,完美。現在它按預期工作! – holden 2009-09-16 11:09:38

5

你真正需要的是attr_accessor:確認。 attr_accessible和attr_accessor之間有區別。

attr_accessor :confirmation 

是相同

def confirmation 
    @confirmation 
end 

def confirmation=(value) 
    @confirmation = value 
end 

現在,因爲它是這樣介紹了該helper方法的通用模式紅寶石。

另一方面,Attr_accesible是rails方法,它標記某些字段可以被批量更新。