Home > OS >  Is it possible to get a variable from a model action to the controller?
Is it possible to get a variable from a model action to the controller?

Time:10-07

I am modifying my "save" action in the model, but I need to get in my controller the variable called "@variable" from my save action of the model, is it possible to return the value of a variable to the controller?

this is my action save in model:

  def save
    @variable = "some value"
    if imported_t_stocks.map(&:valid?).all?
      imported_t_stocks.each(&:save!)
      true
    else
      imported_t_stocks.each_with_index do |t_stock, index|
        t_stock.errors.full_messages.each do |msg|
          errors.add :base, "Row #{index   6}: #{msg}"
        end
      end
      false
    end
  end

this is my controller:

  def create
    @t_stocks_import = TStocksImport.new(params[:t_stocks_import])
    if @t_stocks_import.save

 
      redirect_to stocks_path
    else
      redirect_to stocks_path
    end
  end

CodePudding user response:

Yes, you can. Rails models are just like any other Ruby class. Just add to your model:

attr_reader :variable

Then you can access using:

@t_stocks_import.variable

Views directly accessing model attributes is not a good practice, though.

  • Related