2015-04-12 65 views
0

我想將兩個字節(地址和地址)連接成1個字段(位置)。將兩個字節連接成一個用於Rails

我已經創建了下面的代碼在我的腳控制器:

class PinsController < ApplicationController 
    before_action :set_pin, only: [:show, :edit, :update, :destroy, :like, :unlike] 
    before_action :authenticate_user!, except: [:index, :show] 
    before_action :correct_user, only: [:destroy] 
    before_save :set_location 


    def set_location 
     location = "#{address} #{place}" 
     end 

... 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_pin 
     @pin = Pin.find(params[:id]) 
    end 

    def correct_user 
     @pin = current_user.pins.find_by(id: params[:id]) 
     redirect_to pins_path, notice: "It is only allowed to change the restaurants you have added my yourself." if @pin.nil? 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def pin_params 
     params.require(:pin).permit(:description, :image, :name, :address, :place, :postal_code, :telephone_number, :website, :emailadress, :location) 
    end 
end 

我收到此錯誤信息

undefined method `before_save' for PinsController:Class 

有誰知道我在做什麼錯?

回答

1

您正在控制器中使用before_save鉤子而不是模型。 將此代碼移動到您的模型,它應該工作。

class Pin < ActiveRecord::Base 
    before_save :set_location 

    # ... 

    def set_location 
    self.location = "#{address} #{place}" 
    end 
end 
2

before_save是模型的回調,而不是控制器。

你應該這樣做:

class Pin < ActiveRecord::Base 
    before_save :set_location 

    def set_location 
    self.location = "#{self.address} #{self.place}" 
    end 
end 
+0

由於這是一個愚蠢的錯誤;) –

+0

您不必在此明確調用'self'。 –