【问题标题】:Rails error - app not picking up validations and/or error prevention code blockRails 错误 - 应用程序未获取验证和/或错误预防代码块
【发布时间】:2016-09-06 14:24:25
【问题描述】:

我正在构建一个事件应用程序,它在视图中使用简单的表单供用户创建事件。我正在尝试实施验证,以便必须存在某些细节。当我对此进行测试时 - 通过故意遗漏表单的部分 - 我遇到了一大堆问题/错误/错误,这些问题/错误/错误会被抛出。恢复正常的唯一方法是删除'通过控制台的毒性事件。

就好像视图中的验证和错误代码块没有任何效果,事件仍在创建并分配一个 id 并且代码只是中断,创建一个错误,当我故意省略表单的部分时。

不知道为什么会发生这种情况。这是我的相关代码-

EventsController.rb

class EventsController < ApplicationController
before_action :find_event, only: [:show, :edit, :update, :destroy,]
# the before_actions will take care of finding the correct event for us
# this ties in with the private method below
before_action :authenticate_user!, except: [:index, :show]
# this ensures only users who are signed in can alter an event



def new
    @event = current_user.events.build
    # this now builds out from a user once devise gem is added
    # after initially having an argument of Event.new
    # this assigns events to users
end

def create
    @event = current_user.events.build(event_params)
    # as above this now assigns events to users
    # rather than Event.new

    if @event.save
        redirect_to @event, notice: "Congratulations, you have successfully created a new event."
    else
        render 'new'
    end
end

private

def event_params
    params.require(:event).permit(:title, :location, :date, :time, :description, :number_of_spaces, :is_free, :price, :organised_by, :url, :image, :category_id)
    # category_id added at the end to ensure this is assigned to each new event created
end

def find_event
    @event = Event.find(params[:id])
end







end

这是我的部分表单,它有一个错误代码块 - 这最初引发了一个错误,指出在期望 2 时传递了 0 个参数。

_form.events.html.erb

<%= simple_form_for(@event) do |f| %>
<% if @event.errors.any? %>
    <h2><%= pluralize(@event.errors.count, "error") %> prevented this Event from saving:</h2>
    <ul>
        <% @event.errors.full_message.each do |message| %>
        <li><%= message %></li>
        <% end %>
    </ul>
<% end %>

<%= f.collection_select :category_id, Category.all, :id, :name, {prompt: "Choose a category"} %>
<!-- The above code loop assigns a category_id to each event -->

<%= f.input :image, as: :file, label: 'Image' %>
<%= f.input :title, label: 'Event Title' %>
<label>Location</label><%= f.text_field :location, id: 'geocomplete' %></br>
<label>Date</label><%= f.text_field :date, label: 'Date', id: 'datepicker' %>
<%= f.input :time, label: 'Time' %>
<%= f.input :description, label: 'Description' %>
<label>Number of spaces available</label><%= f.text_field :number_of_spaces, label: 'Number of spaces' %>
<%= f.input :is_free, label: 'Tick box if Event is free of charge' %>
<!--f.input :currency, :collection => [['£GBP - British Pounds',1],['$USD - US Dollars',2],['€EUR - Euros',3]] -->
<%= f.input :price, label: 'Cost per person (leave blank if free of charge)' %>
<%= f.input :organised_by, label: 'Organised by' %>
<%= f.input :url, label: "Link to Organiser site" %>

<%= f.button :submit, label: 'Submit' %>

<% end %>   

带有验证的事件模型。无论是否包含验证,都会出现错误(我已将它们取出并尝试了相同的结果)。

事件.rb

class Event < ActiveRecord::Base

belongs_to :category
belongs_to :user
has_many :bookings
has_many :comments


has_attached_file :image, styles: { medium: "300x300>" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/

validates_associated :category
validates :title, :description, :location, :date, :time, :number_of_spaces, :price_pennies, presence: true


monetize :price_pennies
# required for money-rails gem to function

end

错误消息似乎在我的显示页面中的一行代码中从“ActionController::InvalidAuthenticityToken”到“未定义的方法”到处反弹 -

<p><%= @event.date.strftime('%A, %d %b %Y') %></p>

当我尝试将日期字段留空时。

【问题讨论】:

  • 您能否显示一些错误消息并省略与问题无关的代码? (如控制器显示/索引/编辑/更新/销毁)。关于真实性令牌:提交表单时它是否存在于 HTML 中。是否提交给控制器?
  • 如何在此处显示错误代码?我已经通过删除控制台中的事件来修复错误,但知道它会再次发生。与事件控制器中的创建操作相关的真实性令牌的错误。我会更新我对相关代码的回答。
  • 我得到的第一个错误是这个-
  • ArgumentError - 在 Events#create 中,参数数量错误(给定 0,预期为 2),它在我的代码中突出显示了这行,格式为 partial -

标签: ruby-on-rails ruby validation ruby-on-rails-4 model-view-controller


【解决方案1】:

您认为这是您的问题:

<%= simple_form_for(@event) do |f| %>
<% if @event.errors.any? %>
    <h2><%= pluralize(@event.errors.count, "error") %> prevented this Event from saving:</h2>
    <ul>
        <% @event.errors.full_message.each do |message| %>
        <li><%= message %></li>
        <% end %>
    </ul>
<% end %>

具体来说,这部分:

<% @event.errors.full_message.each do |message| %>

放大:

@event.errors.full_message

您忘记了方法名称末尾的“s”,应该是:

@event.errors.full_messages

full_message 方法采用 2 个参数,用于返回给定属性的单个完整错误消息。这个错字给了你错误。

http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-full_message

【讨论】:

  • 非常感谢 - 我也发现了这一点(请参阅上面的 cmets),但非常感谢我标记为正确的详细答案。请随意详细回答我的任何其他问题,我一直在学习:)
  • @Mike.Whitehead 我强烈建议在其自己的 stackoverflow 问题中发布每个问题和问题。如果有人正在寻找相同问题的解决方案,这使我们更容易回答,并且对社区整体来说更好。
  • 这就是我所做的。有没有办法在这里向特定用户询问您提出的问题?我在这里提出了几个没有回应的问题,但我仍在尝试找出解决方案。
猜你喜欢
  • 1970-01-01
  • 2012-04-16
  • 2011-11-30
  • 2018-06-18
  • 2022-01-05
  • 2012-01-14
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多