Ruby on rails 在rails中创建后,如何将即时变量从控制器发送到方法?

Ruby on rails 在rails中创建后,如何将即时变量从控制器发送到方法?,ruby-on-rails,model,after-create,Ruby On Rails,Model,After Create,在rails中创建后,如何将即时变量从控制器发送到方法 如果我有这样的控制器: 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"

在rails中创建后,如何将即时变量从控制器发送到方法

如果我有这样的控制器:

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
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
我有这样的模型:

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
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
谢谢,您需要使用

您的问题是无法访问模型中的@instance\u变量。它是-您的模型设置数据的一部分,而不是相反

使您的数据在模型中可访问的方法是使用分配给模型中attr_accessor方法的:

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

    def get_url
        self.url
    end
end
如果希望访问模型中的URL变量,则必须找到一种方法来持久化数据。这取决于你想要达到的目标。例如,如果要为要创建的对象设置URL,最好在模型中使用after_create回调:

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

    def set_url
       self.url = ...
    end
end
顺便说一句,它是实例变量:它是对象实例的变量