0

我想从 Rails 内的模型文件中运行 Render 和 flash 等方法。我的代码是这样的:

class Product < ActiveRecord::Base
attr_accessible :name, :price, :released_on
validates :name, uniqueness: true

def self.to_csv(options = {})
 CSV.generate(options) do |csv|
  csv << column_names
  all.each do |product|
    csv << product.attributes.values_at(*column_names)
  end
end
end



def self.import(file)
CSV.foreach(file.path , headers:true) do |row|
  @product=Product.new(row.to_hash)
  if @product.valid?
     @product.save
    flash[:notice] = "Product created!"
    redirect_to(@product) and return
else

 redirect_to action: :index
 end
 end
 end
 end

当我运行它并输入模型时,我收到 Flash 方法的错误。同样未定义渲染方法。任何猜测。

4

1 回答 1

1

简短的回答:你没有。

更长的答案:您正在尝试以不适合 Rails 工作方式的方式做事。显示的事物与这些事物背后的数据之间存在非常牢固的分离。

你需要重新思考这些东西是如何组合在一起的。控制器负责处理模型,然后准备信息以供视图显示。与其在模型中创建闪光灯,不如使用控制器找出产品是否已创建并允许其显示闪光灯。

于 2013-08-01T19:42:46.423 回答