2015-04-12 28 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'。 –