2012-11-21 57 views
4

拳頭,我使用rails 3.0.9和ruby 1.8.7。 我需要一些幫助,因爲我無法驗證並完全向我的用戶顯示在屏幕上。Rails 3:驗證關聯並向用戶顯示完美驗證

模型:

class Book < ActiveRecord::Base 
    belongs_to :genre 
    validates_presence_of :title, :genre 
    attr_accessible :genre_id 
end 

以下形式:

<div class="field"> 
    <%= f.label :genre %><br /> 
    <%= f.collection_select(:genre_id, Genre.all(:order => :name), :id, :name, :prompt => 'Select') %> 
</div> 

當我發送在空白的形式(使用默認selectioned提示值)完美顯示錯誤消息「流派不能空白「,但在我收到的HTML形式,如:

<div class="field"> 
    <div class="field_with_errors"> 
     <label for="book_genre">Genre</label> 
    </div> 
    <br> 
    <select name="book[genre_id]" id="book_genre_id"> 
     <option value="">Select</option> 
     <option value="2">Gramatic</option> 
     <option value="1">Terror</option> 
    </select> 
</div> 

我需要選擇字段div.field_with_erros也是因爲我在CSS中定義的紅色背景。

之後,我試圖改變f.collection_select:genre_id到:體裁

現在,我得到了div.field_with_erros內選擇欄。 Owwww yeahhh勝利了一會兒,直到我意識到驗證總是指責錯誤,導軌並不知道select字段:genre是:genre_id它所尋找的。

我的問題是:如何使:genre更改爲:genre_id驗證中?或者你們所有人都有更好的方式來做到這一點?

繼續進行測試我嘗試將標籤和collection_select更改爲genre_id,驗證工作完美,但未生成帶div.field_with_errors的html,因此我試圖將:genre_id放入validates_presence_of,現在它看起來像: 「validates_presence_of:title,:genre,:genre_id」。

大,但是......

  1. 當我提交表單,不得不選擇默認提示值 驗證工作正常,但他們指控2個錯誤,一個到:體裁和 另一個:genre_id (¬¬)但html很好,標籤和 選擇是在div.field_with_erros中。

  2. 如果我提交表格並從流派中選擇了一些值 驗證和html是好的。

  3. 如果我提交表單,但我有一些選項的值更改爲一個無效的 測試,如果模型之間的驗證工作驗證確實 工作正常,但HTML不創建div.field_with_erros。

任何人都可以幫助我嗎? (是的,我的英文不是最好的,對不起!)

回答

1

我創建了一些腳手架模型來測試它。我設置2遷移:

class CreateGenres < ActiveRecord::Migration 
    def change 
    create_table :genres do |t| 
     t.string :title 
     t.timestamps 
    end 
    end 
end 

class CreateBooks < ActiveRecord::Migration 
    def change 
    create_table :books do |t| 
     t.string :name 
     t.references :genre 
     t.timestamps 
    end 
    end 
end 
形式

我:

<%= f.label :genre_id %> 
<%= f.collection_select(:genre_id, Genre.all(:order => :title), :id, :title, :prompt => 'Select') %> 

而在車型我有:

class Genre < ActiveRecord::Base 
    attr_accessible :title 
    has_many :books 
end 

class Book < ActiveRecord::Base 
    belongs_to :genre 
    validates_presence_of :name, :genre_id 
    attr_accessible :name, :genre_id 
end 

驗證然後就像我所期望的......

+0

您好克里斯, 我想你的解決方案,我得到了最壞的結果。我認爲這不是我正在尋找的,因爲如果我不驗證:通常用戶可以選擇一個已被排除的基因,或者他們可以通過檢查元素(螢火蟲)將值更改爲另一個。如果這不是我想的,請你能更好地向我解釋一下嗎? –

+0

對不起,我用錯誤的方式寫了流派,現在我在帖子中修復,這是因爲我來自巴西,所以我已經翻譯成英語,或幾乎翻譯成英語。哈哈哈哈(問題不斷髮生) –

+0

我做了一些真正的測試後重新寫了上面的答案... –

0

我沒有找到任何解決此問題的方法,並決定只檢查錯誤:

<% if f.object.errors.include?(:genre) %> 
    <div class='field_with_errors'> 
<% end %> 
// :genre field 
<% if f.object.errors.include?(:genre) %> 
    </div> 
<% end %> 

一些鏈接:

  1. http://railsguides.net/belongs-to-and-presence-validation-rule1/爲什麼沒有驗證的id但協會本身存在。
  2. https://github.com/frank-west-iii/association_validations驗證id或關聯的區別。
  3. http://iada.nl/blog/article/rails-tip-display-association-validation-errors-fields劫持Rails的方法