将两个字段连接成一个用于Rails的字段

时间:2015-04-12 12:03:43

标签: ruby-on-rails

我想将两个fiels(地址和地点)连接到1个字段(位置)。

我在我的引脚控制器中创建了以下代码:

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

有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:2)

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

你应该这样做:

class Pin < ActiveRecord::Base
  before_save :set_location

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

答案 1 :(得分:1)

您在控制器中使用before_save挂钩而不是模型。 将此代码移动到您的模型,它应该可以工作。

class Pin < ActiveRecord::Base
  before_save :set_location

  # ...

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