显示模态轨道中的错误

时间:2016-10-29 20:26:38

标签: ruby-on-rails ruby

我非常沮丧,因为我已经工作了好几天,但我还没有找到解决方案。

我有一个Visit.rb模型,除了常见的验证之外,我还通过两种方法进行了两次验证(访问的开始日期不能在结束之前,并且不可能有两次访问具有相同的开始日期,结束日期和visitor_id)。

我需要在我给予登记访问的模式中显示我设置的这些错误,但直到现在我从未取得过成功。 实际上每次发生此错误时:VisitsController中的 ArgumentError #create - 表单中的第一个参数不能包含nil或为空

我到目前为止所做的是......

Visit.rb

class Visit < ActiveRecord::Base

    belongs_to          :employee
    belongs_to          :visitor
    default_scope   ->  { order(:created_at) }

    validates   :from,          presence: true,     uniqueness: { scope: [:to, :visitor_id] }
    validates   :to,            presence: true
    validates   :visitor_id,    presence: true
    validates   :employee_id,   presence: true
    validate    :valid_date_range_required
    validate    :visit_uniqueness


    def valid_date_range_required
        if (from && to) && (to < from)
            errors[:base] << "Visit's end date cannot be prior to the start one."
        end
    end


    def visit_uniqueness
        if Visit.find_by(from: :from, to: :to, visitor_id: :visitor_id)
            errors[:base] << "A visit with the same start date, end date and visitor already exists."
        end
    end

end

visits_controller.rb

class VisitsController < ApplicationController
    before_action :logged_in_employee,  only: [:create,    :destroy]
    before_action :correct_employee,    only: [:destroy,   :update ]

    def create
        @visit = current_employee.visits.build(visit_params)
        if @visit.save
            flash[:success] = "Visit added"
            redirect_to employee_path(session[:employee_id], :act => 'guestsVisits')
        else
            @visits = current_employee.visits.all
            @employee = current_employee
            render 'employees/guestsVisits'
        end
    end



    private

        def visit_params
            params.require(:visit).permit(:from, :to, :visitor_id, :employee_id)
        end

        def correct_employee
            @visit = current_employee.visits.find_by(id: params[:id])
            redirect_to root_url if @visit.nil?
        end
end

guestsVisits.rb (我的观点)

<div class="jumbotron3 text-center">
  <div class="row">
    <h1>Guests Visits</h1>
    <hr>
    <%=render :partial =>"layouts/sidebar"%>
    <div class="panel3">
        <div class="panel-body">

                                                    <!-- Modal for Visit -->
                <% if logged_in? %>
                <%=render :partial =>"shared/error_messages"%>

                <a class="btn icon-btn btn-success pos" data-toggle="modal" data-target="#visitModal">
                <span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
                Add a visit
                </a>

                <div id="visitModal" class="modal fade" role="dialog">
                    <div class="modal-dialog">

                        <div class="modal-content">

                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                <h4 class="modal-title">Add Visit</h4>
                            </div>

                            <div class="modal-body">
                                <%= form_for(@visit) do |f| %>

                                    <%= f.label :start_date %>
                                    <%= f.date_field :from, class: 'form-control',:value => (f.object.from.strftime('%m/%d/%Y') if f.object.from) %>
                                    <%= errors_for @visit, :from %><%if @visit.errors.any?%><br><%end%>

                                    <br>
                                    <%= f.label :end_date %>
                                    <%= f.date_field :to, class: 'form-control',:value => (f.object.to.strftime('%m/%d/%Y') if f.object.to) %>
                                    <%= errors_for @visit, :to %><%if @visit.errors.any?%><br><%end%>

                                    <br>
                                    <%= f.label :Visitor %>
                                    <%= f.collection_select :visitor_id, Visitor.all, :id, :full_name, { :class=> "form-control", :include_blank => ''}%>
                                    <%= errors_for @visit, :visitor_id %><%if @visit.errors.any?%><br><%end%>
                                    <br>
                                    <%= f.submit "Add visit", class: "btn btn-primary btn-color" %>
                                <% end %>
                            </div>

                            <div class="modal-footer">
                                <button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
                            </div>

                        </div>
                    </div>
                </div>
                <% end %>
            </div>
        </div>
    </div>
</div>

我尝试使用两个不同版本的error_messages.rb

error_messages.rb(1)

<% if @visit && @visit.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      The form contains <%= pluralize(@visit.errors.count, "error") %>.Open the modal for more details
    </div>
  </div>
<% end %>

error_messages.rb(2)

<% if @visit.errors.any? %>
    <ul class="errors">
    <% @visit.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
    <% end %>
    </ul>
<% end %>

我希望有人可以帮助我,因为我不明白如何解决这个问题。 非常感谢你。

修改

class Employee < ActiveRecord::Base

  before_save { self.email = email.downcase }
  before_create :confirmation_token

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  has_many :macaddresss,    dependent:      :destroy
  has_many :visits,         dependent:      :destroy
  has_many :visitors,       dependent:      :destroy

  #Validations
  validates :name,  presence: true , length: { maximum:20 , minimum: 2 }
  validates :lastname,  presence: true, length: { maximum:20 , minimum: 2 }
  validates :gender,  presence: true
  validates :dateofbirth,  presence: true
  validates :birth_country,  presence: true
  validates :birth_place,  presence: true, length: { maximum:60}
  validates :contry_of_residence,  presence: true
  validates :city_of_residence,  presence: true, length: { maximum:60 }
  validates :address,  presence: true, length: { maximum:60 , minimum: 7 }
  validates :email,  presence: true, length: { maximum:243 } ,format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
  validates :password, length: { minimum: 6 }
  validates :terms_of_service, acceptance: { message: 'accept terms and conditions' }

  [...]

  has_secure_password

  def Employee.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end
end

session_helper.rb

  def current_employee
    @current_employee ||= Employee.find_by(id: session[:employee_id])
  end

EDIT2:

employees_controller.rb

class EmployeesController < ApplicationController

    def show

        if logged_in?
            @employee = Employee.find(params[:id])
            @indirizzimac = current_employee.indirizzimacs.new
            @visitor = current_employee.visitors.new
            @visit = current_employee.visits.new
            @visits = current_employee.visits.all
            if params[:act]=='myData'
                render 'myData'
            elsif params[:act]=='myNetwork'
                    render 'myData'
            elsif params[:act]=='temporaryUsers'
                render 'temporaryUsers'
            elsif params[:act]=='guestsVisits'
                render 'guestsVisits'
            elsif params[:act]=='myAccount'
                render 'myAccount'
            else
                render 'show'
            end
        else
            render 'static_pages/errorPage'
        end
    end
end

1 个答案:

答案 0 :(得分:1)

从我所看到的如果创建访问失败,您实例化@visits@employee实例变量,然后呈现&#39; employees / guestsVisits&#39;它使用@visit的视图,我认为它不存在于empleyees控制器中 所以添加广告

def guestsVisits
  @visit = current_employee.visits.build
end