【问题标题】:Rails 3.2.x render another template view with specific idRails 3.2.x 渲染另一个具有特定 id 的模板视图
【发布时间】:2013-02-09 14:09:14
【问题描述】:

我正在尝试以下代码串:

class AppointmentsController < ApplicationController

def create
    @appointment = Appointment.new(params[:appointment])
    @current_patient = @appointment.patient_id
    if @appointment.save
        flash[:success] = "Appointment scheduled!"
        redirect_to patient_path(@current_patient)
    else
        render 'patients/show'
    end
end

目前正在通过三个控制器。其中两个似乎很重要。

class Appointment < ActiveRecord::Base
  attr_accessible :appointment_date, :appointment_notes, :appointment_time, :procedure_id, :patient_id
  belongs_to :patient
  belongs_to :procedure

  validates :procedure_id, presence: true
  validates :patient_id, presence: true
  validates :appointment_date, presence: true
  validates :appointment_time, presence: true
class Patient < ActiveRecord::Base
  attr_accessible :address1, :address2, :city, :comment, :email, :first_name, :init_date, :init_time, :last_name, :mobile, :notes, :phone, :state, :zip
  before_validation :upcase_patient
  before_save { self.email.downcase! }
  has_many :appointments, dependent: :destroy
  has_many :procedures, through: :appointments

我的创建方法效果很好。但是,当我提交数据并且未在约会中通过验证时,它应该呈现正确的 app.dev/patients/:id 页面,其中 :id 是我正在使用的当前页面。有问题的表格是创建约会的表格(通过患者/显示视图)。当提交不正确或零数据并且需要存在:true 时,我希望呈现相同的页面。我目前收到的是:

rspec

ActionView::Template::Error:
   undefined method `first_name' for nil:NilClass
 # ./app/views/patients/show.html.erb:1:in `_app_views_patients_show_html_erb__4137167421928365638_70201005779320'
 # ./app/controllers/appointments_controller.rb:11:in `create'

我怀疑这与能够在正确的路径上相应地设置渲染有关,特别是调用正确的患者/ID。任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails-3.2 rspec2 rails-activerecord actionview rails-models


    【解决方案1】:

    您最可能的问题是您在 patients/show 中使用了在验证失败并呈现模板时未在创建操作中声明的变量。解决此问题的最佳方法是在验证失败时在 create 操作上声明用于 show 操作的相同变量集

    def show
      @patients = ...
      @files = ...
    end
    
    def create
      if @object_that_fails_validation.save
      else
        @patient = ...
        @files = ...
        #render the show action
      end
    end
    

    如果您觉得这不是 DRY,尤其是当您声明大量变量时,请通过 ajax 提交表单或将变量移动到其他方法

    def show
      set_variables
    end
    
    def create
      if @object_that_fails_validation.save
      else
        set_variables
        #render the show action
      end
    end
    
    protected
    
    def set_variable
      @patient = ...
      @files = ...
    end
    

    【讨论】:

    • 效果很好。谢谢,但确实按照您的建议将变量设置为 private 而不是 protected。总而言之,这一切都很顺利!干杯!
    猜你喜欢
    • 2016-11-02
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多