【问题标题】:using an instance of appointment in the appointment model在约会模型中使用约会实例
【发布时间】:2019-05-24 10:06:12
【问题描述】:

我创建了一个带有一些单选按钮的表单,并且必须将appointment.id 插入单选按钮和标签中。但是,Rails 抛出错误:

未定义方法cancel_3 用于约会。

所以我尝试在Appointment 模型中创建一个方法来解决这个问题,方法是使用define_method(见下文)。但是,由于这是在模型中,我无法在此处使用约会实例。

我有什么办法可以完成这项工作吗?

 define_method "cancel_#{appointment.id}" do
   # ...
 end
<%= f.radio_button "cancel_#{appointment.id}", :true %>
<%= f.label "cancel_#{appointment.id}_true", "Yes", class: "modal-options cancel" %>
<%= simple_form_for :appointment, url: delete_admin_appointment_path(appointment) do |f| %>

【问题讨论】:

  • 你正在尝试调用模型的方法但你在视图层,你可以调用路由/页面(最后是控制器操作)
  • 在那个动作中你可以调用你模型的方法
  • 感觉就像XY problem。方法名称不应包含其参数。为什么不定义返回appointment.id 的方法cancel_id(假设您的模型has_onebelongs_to:appointment)?

标签: ruby-on-rails ruby methods model


【解决方案1】:

更新您的表单

<%= simple_form_for @appointment, url: delete_admin_appointment_path(@appointment) do |f| %>

在你的控制器中

def new
  @apointment = Apointment.new
end

和单选按钮

<%= f.radio_button "cancel_#{@appointment.id}", :true %>
<%= f.label "cancel_#{@appointment.id}_true", "Yes", class: "modal-options cancel" %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 2018-06-15
    • 2015-09-06
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多