模型中定义的方法未被控制器找到

时间:2016-06-28 18:56:26

标签: ruby-on-rails

Rails 3.2

在我的controllers / tickets_controller.rb中,我有:

def update
  @ticket = Ticket.find(params[:id])
  @ticket.save_customer_info_if_present(params, @ticket)
  respond_to do |format|
    if @ticket.update_attributes(params[:lead_billing])
      format.html { redirect_to @ticket, notice: 'Ticket was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: "edit" }
      format.json { render json: @ticket.errors, status: :unprocessable_entity }
    end
  end
end  

在我的models / ticket.rb中,我有:

def self.save_customer_info_if_present(params, ticket)
  customer_info_params = params[:customer_info]
  if !customer_info_params.nil?
    customer_info = CustomerInfo.new(
        :ticket_id => ticket.id,
        :first => customer_info_params["first"],
        :last => customer_info_params["last"],
        :status => 'entered'
    )
    customer_info.save
  end
end  

运行更新操作时,我找不到找到的"方法:save_customer_info_if_present"

为什么控制器找不到模型中定义的自我方法?

1 个答案:

答案 0 :(得分:2)

您在模型的实例上调用方法:

  @ticket.save_customer_info_if_present(params, @ticket)

但是将此方法定义为类方法:

def self.save_customer_info_if_present(params, ticket)
    # some code here

从方法定义中删除self关键字,您也可以删除故障单参数,因为您已在故障单实例上调用此方法(使其更具可读性):

def save_customer_info_if_present(params)
  if params[:customer_info].present?
    customer_info = CustomerInfo.new(
        :ticket_id => id, # just an id because it in the ticket instance
        :first => params[:customer_info]["first"],
        :last => params[:customer_info]["last"],
        :status => 'entered'
    )
    customer_info.save
  end
end  

<子> Class and Instance Methods in Ruby