拳头,我使用的是 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 更改为流派_id,验证工作完美,但没有生成带有 div.field_with_errors 的 html,所以我尝试将 :genre_id 放在 validates_presence_of 中,所以现在它看起来像:“validates_presence_of :title , :genre, :genre_id"。
很棒,但是...
验证工作正常,但他们指责 2 个错误,一个是 :genre 和
另一个到 :genre_id (¬¬) 但 html 很好,标签和
选择在 div.field_with_erros 内。
验证和 html 没问题。
测试模型之间的验证是否真的有效
工作正常,但 html 没有创建 div.field_with_erros。
任何人都可以帮助我,好吗?
(是的,我的英语不是最好的。对不起!)
最佳答案
我创建了一些脚手架模型来测试这一点。我设置了 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
然后验证按我的预期工作......
关于ruby-on-rails - rails 3 : Validate association and show perfectly the validation to the user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13496893/