0

由于某种原因,我的验证错误消息没有显示在窗口上。它与 twitter-bootstrap 有什么关系吗?我记得看过一些视频教程,但不幸的是现在找不到。

_form 部分记录

<%= form_for [@estate,@record] do |f| %>
      <% if @record.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(@record.errors.count, "error") %> prohibited this record from being saved:</h2>

          <ul>
          <% @record.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
          <% end %>
          </ul>
        </div>
      <% end %>
    .......
    ......
    ...
    <% end %>

我的唱片模型

validates :E1, presence: true
      validates :E2, presence: true
      validates :E3, presence: true
      validates :E4, presence: true
      validates :R1, presence: true
      validates :R2, presence: true
      validates :R3, presence: true
      validates :R4, presence: true
      validates :Year, presence: true
      validate :validation

控制器的创建和更新方法

def create
        @record = @estate.records.build(params[:record])

        respond_to do |format|
          if @record.save
            format.html { redirect_to [@estate,@record], notice: 'Record was successfully created.' }
            format.json { render json: @record, status: :created, location: @record }
          else
            format.html { render action: "new" }
            format.json { render json: @record.errors, status: :unprocessable_entity }
          end
        end
      end

      # PUT /records/1
      # PUT /records/1.json
      def update
        @record = Record.find(params[:id])

        respond_to do |format|
          if @record.update_attributes(params[:record])
            format.html { redirect_to [@estate,@record], notice: 'Record was successfully updated.' }
            format.json { head :no_content }
          else
            format.html { render action: "edit" }
            format.json { render json: @record.errors, status: :unprocessable_entity }
          end
        end
      end

记录属于遗产和遗产有很多记录有什么关系。就像在创建记录时我做的“@record = @estate.records.build(params[:record])”我尝试使用调试器调试它,我发现在创建记录时它不会进入其他部分,它直接创建记录而不检查记录模型的验证。

4

1 回答 1

0

看看这个宝石http://rubygems.org/gems/dynamic_form

它将在您的视图中为您显示验证错误。然后,您可以删除在您的实例错误上循环的代码。

此外,这里与您的问题无关,但我建议使用以下代码重构您的代码:

在您的控制器中:

respond_to :html, :json

def create
  @record = @estate.records.build(params[:record])
  if @record.save
    # flash[:success]... or whatever
  else
    # flash[:alert]... or whatever
  end

  respond_with @record
end

# same for your update method

为了您的信息,您可以替换render action: 'new'render :new

于 2013-06-25T20:11:05.577 回答