Active Record属性的值未正确保存

时间:2014-04-11 02:26:44

标签: ruby-on-rails ruby

在下面的代码中,我尝试为popup对象设置Company变量,但当前它位于的位置,当用户点击提交按钮时,它不会被设置创建公司对象的页面。

当我在if语句之前放置该行时,弹出变量已设置,但由于尚未保存该对象,因此@company.id已设置,因此该部分我试图创建的弹出字符串没有正确设置。

有关如何正确设置弹出变量的任何想法?

def create
    @company = Company.new(company_params)
    if @company.save
        redirect_to map_path
        flash[:success] = "Company Successfully Added"
        @company.popup = "<h3><a href='companies/#{@company.id}'>#{@company.name}</a></h3>"
    else
        render 'new'
    end
end

1 个答案:

答案 0 :(得分:1)

如果popup是公司属性,如果您需要保存,只需使用'before_save'

def create
    @company = Company.new(company_params)
    if @company.save
        redirect_to map_path
        flash[:success] = "Company Successfully Added"
    else
        render 'new'
    end
end

<强>型号:

before_save :set_popup_value

private

def set_popup_value
  popup = "<h3><a href='companies/#{self.id}'>#{self.name}</a></h3>"
  #self.update_attributes(:popup => popup)
  self.update_column(:popup => popup)
end

否则,如果您希望'popup'只显示它而不是保存在数据库中,那么您必须使用attr_accessor

<强>型号:

class Company < ActiveRecord::Base
  attr_accessor :popup
end

<强>控制器:

def create
    @company = Company.new(company_params)
    if @company.save
        @company.popup = "<h3><a href='companies/#{@company.id}'>#{@company.name}</a></h3>"
        redirect_to map_path
        flash[:success] = "Company Successfully Added"
    else
        render 'new'
    end
end

希望有所帮助:)