1

how to send instant variable from controller to methods after create in rails?

if i have controller like this :

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :set_url

  def set_url
    @url = if request.url.include?("http://localhost:3000/")
      "http://localhost:3000"
    else
      "http://tester.com"
    end
  end
end

and i have model like this :

class Article < ActiveRecord::Base
  after_create :get_url

  def get_url
    // how to get instant variable @url from before filter in application controller to this method ?
  end
end

thanks before

3lviend
  • 243
  • 5
  • 13

1 Answers1

0

You'll need to use attr_accessor

The problem you have is you can't access @instance_variables in your model. It's part of the MVC design pattern - your model sets the data, not the other way around

The way to make your data accessible inside your model is to use a virtual attribute, assigned with the attr_accessor method in your model:

#app/models/article.rb
Class Article < ActiveRecord::Base
    attr_accessor :url

    def get_url
        self.url
    end
end

This will allow you to do this in the controller:

  before_filter :set_url

  def set_url
    @article = Article.new
    @article.url = if request.url.include?("http://localhost:3000/")
      "http://localhost:3000"
    else
      "http://tester.com"
    end
  end

If you wanted to access the URL var inside your model, you'll have to find a way to persist the data. This depends on what you're trying to achieve. For example, if you're looking to set the URL for an object that you wish to create, you may be better using the after_create callback inside the model:

#app/models/article.rb
Class Article < ActiveRecord::Base
    after_create :set_url
    attr_accessor :url

    def set_url
       self.url = ...
    end
end
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147