2012-04-21 39 views
2

因爲我對Ruby on Rails很新,我會解釋我做了什麼。我在我的模型中有一個虛擬屬性,名爲測試。我這樣定義它:虛擬屬性allways無自定義驗證方法

class Comment < ActiveRecord::Base 
    attr_accessor :testing 
    attr_accessible :user_name, :comment, :user, :testing 

然後我添加了自定義方法,這樣的自定義驗證:

validate :custom_validation 

我還添加過程的方法,:

def custom_validation 
    # a bit of custom_validation 
end 

我然後在我的表單中添加一個字段:

<%= form_for(@comment) do |f| %> 
    <%= render 'shared/error_messages', :object => f.object %> 
    <%= f.hidden_field :post_id, :value => @post.id %> 
    <% if !signed_in? %> 
      <div class="field"> 
        <%= f.label :user_name %> 
        <%= f.text_field :user_name, :class => "user_field" %> 
      </div> 
    <% else %> 
      <%= f.hidden_field :user_id, :value => current_user.id %> 
    <% end %> 
      <div class="field"> 
        <%= f.label :comment %> 
        <%= f.text_area :comment, :style => "height: 50px; width: 80%;" %> 
      </div> 
      <div class="field pin"> 
        <%= f.label :testint %> 
        <%= f.text_field :testing, :class => "user_field" %> 
      </div> 
    <div class="buttons"> 
      <%= f.submit "Speichern" %> 
    </div> 
<% end %> 

這就是我所做的一切。所以,請不要以爲我沒有別的東西,我沒有在這裏描述,因爲我沒有;)

我的問題是,我的虛擬現場測試總是無我custom_validation方法裏面。除非我在控制檯上運行驗證:

co = Comment.new 
co.testing = "Hello" 
co.valid? 

我檢查過使用記錄器。如果我通過控制檯運行測試-場不是零。如果我通過瀏覽器運行它,它是。看起來該參數以某種方式不能正確傳遞給模型。我希望我錯過了一些非常明顯的東西。希望您能夠幫助我。

乾杯, 邁克爾

+0

你的創建/更新操作是什麼樣的? – 2012-04-21 22:43:32

回答

0

它與您創建或更新操作中的內容有關。腳手架生成器將放置代碼來設置實際屬性,但不會從attr_accessor調用setter方法。

+0

我acalally只是忘記設置字段值的行動* facepalm * – 2012-04-22 08:42:06

0

添加attr_reader :testing到你的模型!

+0

爲什麼?這不會有幫助,因爲'attr_accessor'是'attr_reader'和'attr_writer'。 OMG !!! – klump 2012-04-21 22:54:07