加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 3:验证关联并完美地向用户显示验证

发布时间:2020-12-17 02:03:29 所属栏目:百科 来源:网络整理
导读:拳头,我使用的是rails 3.0.9和 ruby 1.8.7. 我需要一些帮助,因为我无法验证并在屏幕上完美地显示给我的用户. 该模型: class Book ActiveRecord::Base belongs_to :genre validates_presence_of :title,:genre attr_accessible :genre_idend 表格: div clas
拳头,我使用的是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中的select字段,因为我在CSS中定义了红色背景.

之后我尝试将f.collection_select:genre_id更改为:genre

现在我在div.field_with_erros中找到了select字段.哦,是的,胜利,一会儿,直到我意识到验证总是指责错误,导轨不知道选择字段:流派是:genre_id它寻找.

我的问题是:如何使:类型更改为:genre_id验证?或者你们所有人都有更好的方法吗?

继续测试我尝试将标签和collection_select更改为genre_id,验证工作完美,但没有使用div.field_with_errors生成html所以我试图将:genre_id放在validates_presence_of中,所以现在它看起来像:“validates_presence_of:title,:genre,:genre_id“.

很棒,但……

>当我提交表单并选择了默认提示值时
验证工作正常,但他们指责2个错误,一个到:流派和
另一个:genre_id(??)但html很好,标签和
select位于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),: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

验证然后按照我的预期工作……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读