如何在模型中运行Render和flash等方法

时间:2013-08-01 19:23:38

标签: ruby-on-rails ruby-on-rails-3

我想从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方法。类似的渲染方法未定义。任何猜测。

1 个答案:

答案 0 :(得分:1)

简短的回答:你没有。

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

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