Rails, How to render a view/partial in a model

前端 未结 10 1801
不思量自难忘°
不思量自难忘° 2020-12-22 18:55

In my model I have:

after_create :push_create

I push_create I need to render a view. I\'m trying to do that like so:

  def         


        
10条回答
  •  暖寄归人
    2020-12-22 19:33

    Rails 5 way

    In Rails 5 rendering outside a controller became pretty straightforward due to implemented render controller class method:

    # render template
    ApplicationController.render 'templates/name'
    # render action
    FooController.render :index
    # render file
    ApplicationController.render file: 'path'
    # render inline
    ApplicationController.render inline: 'erb content'
    

    When calling render outside of a controller, one can assign instance variables via assigns option and use any other options available from within a controller:

    ApplicationController.render(
      assigns: { article: Article.take },
      template: 'articles/show',
      layout: false
    )
    

    Request environment can be tailored either through default options

    ApplicationController.render inline: '<%= users_url %>'
    # => 'http://default_host.com/users'
    
    ApplicationController.renderer.defaults[:http_host] = 'custom_host.org'
    # => "custom_host.org"
    
    ApplicationController.render inline: '<%= users_url %>'
    # => 'http://custom_host.org/users'
    

    or explicitly by initializing a new renderer

    renderer = ApplicationController.renderer.new(
      http_host: 'custom_host.org',
      https: true
    )
    renderer.render inline: '<%= users_url %>'
    # => 'https://custom_host.org/users'
    

    Hope that helps.

提交回复
热议问题