Ruby on rails Rails通过before_操作设置局部变量,而不使用实例变量

Ruby on rails Rails通过before_操作设置局部变量,而不使用实例变量,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我对ruby还是很陌生&对rails还是很陌生,并尝试了一些东西——我不确定它是否真的可行(甚至有用): 我想在before_操作中设置变量,但我不希望它们是实例变量,而是稍后通过render locals:{}在视图中呈现 控制器 before_action :set_image_and_location, only: [:new, :my_method] def new render locals: { image: image, location: location } end d

我对ruby还是很陌生&对rails还是很陌生,并尝试了一些东西——我不确定它是否真的可行(甚至有用):

我想在before_操作中设置变量,但我不希望它们是实例变量,而是稍后通过
render locals:{}
在视图中呈现

控制器

before_action :set_image_and_location, only: [:new, :my_method]

def new
  render locals: { image: image, location: location }
end

def my_method
  # do other stuff
  render locals: { image: image, location: location }
end

private

def set_image_and_location
  image = Image.find_or_initialize_by(params[:id])
  location = Location.find(image.location_id)
end

那么,我如何在不使用实例变量的情况下,将它们从“set_image_和_location”转移到方法中呢?或者这是不可能的,或者通常是一个坏主意?

有一个gem,我认为它可能适合您的用例-体面的曝光

expose(:image) do
  Image.find_or_initialize_by(params[:id])
end
expose(:location) do
  Location.find(image.location_id)
end

我已经配置了通过
before\u action
钩子预设
局部变量的功能,方法是使用自定义函数进行渲染(例如
render\u with\u locals
)和实例变量
@\u locals
作为临时存储:

before_action :set_common_locals

def new
  render_with_locals
end

def my_method
  render_with_locals
end

# You can replace any parameter or add some new parameters
def my_other_method
  render_with_locals locals: { image: image2, other_option: other_option }
end

private

def render_with_locals(*args)
  options = args.extract_options!
  locals = options[:locals] || {}
  options[:locals] = @_locals.merge(locals)
  render(*args, options)
end

def set_common_locals
  @_locals ||= {
    image: image,
    location: location,
  }
end

嘿,亚当,谢谢你的回答。实际上,我更感兴趣的是我自己如何做到这一点——为了学习和理解:)