2016-06-28 60 views
0
Rails 3.2 

在我的控制器/ 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 

而且在我的模型/ 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」

爲什麼不是控制器fin在模型中定義的自我方法?

回答

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

+0

是的。謝謝。當我第一次寫這篇文章的時候,我只是通過了ticket ID,現在我正在通過@ticket,但忘記了它改變了一切。奇怪的部分,是它工作了一段時間。 – EastsideDeveloper