5

拳头,我正在使用 rails 3.0.9 和 ruby​​ 1.8.7。我需要一些帮助,因为我无法验证并在屏幕上完美地向我的用户展示。

该模型:

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>

当我以空白形式发送表单(默认选择提示值)时,错误消息完美显示“类型不能为空白”,但在表单中我收到的 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 更改为 :genre

现在我得到了 div.field_with_erros 中的选择字段。Owwww 是的,胜利了一会儿,直到我意识到验证总是指责错误,rails 不知道选择字段 :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_id”。

很好,但是...

  1. 当我提交表单并选择默认提示值时,验证工作正常,但他们指责 2 个错误,一个到 :genre,另一个到 :genre_id (¬¬) 但 html 很好,标签和选择在 div 内.field_with_erros。

  2. 如果我提交表单并从类型中选择了一些值,则验证和 html 就可以了。

  3. 如果我提交了表单,但我将某个选项的值更改为一个无效,以测试模型之间的验证是否有效,则验证确实可以正常工作,但 html 没有创建 div.field_with_erros。

任何人都可以帮助我,好吗?(是的,我的英语不是最好的。对不起!)

4

2 回答 2

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

然后验证按我的预期工作......

于 2012-11-21T16:24:24.970 回答
1

我没有找到解决此问题的任何方法,并决定只检查视图中的错误:

<% 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 方法
于 2017-07-14T17:32:11.233 回答