如何从控制器中包含的模块渲染js模板? [英] How to render js template from module included in controller?

查看:102
本文介绍了如何从控制器中包含的模块渲染js模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器问题中有一个动作,该动作已包含在控制器中.此操作不会呈现出response_to块下指定的js.erb文件. 如何正确处理控制器问题以成功呈现js.erb文件(或任何视图)?我的路线是否有问题?

I have an action in a controller concern, which gets included in a controller. This action does not render a js.erb file as specified under a respond_to block. How do I properly get an action in a controller concern to successfully render a js.erb file (or any view, for that matter)? Is it a problem with my routes?

模块操作的链接

= link_to image_tag("upvote.png"), 
send("vote_socionics_#{votable_name}_path", votable, vote_type: "#{s.type_two_im_raw}"),           
id: "vote-#{s.type_two_im_raw}",           
method: :post,          
remote: true

**控制器操作的链接**

** The link for the controller action**

= link_to "whatever", characters_whatever_path, remote: true

controllers/characters_controller.rb

class CharactersController < ApplicationController
  include SocionicsVotesConcern

  def an_action
    respond_to do |format|
      format.js { render 'shared/vote_socionics' }   # This renders/executes the file
    end
  end

控制器/问题/socionics_votes_concern.rb

module SocionicsVotesConcern
  extend ActiveSupport::Concern

  def vote_socionics
    respond_to do |format|
      format.js { render 'shared/vote_socionics' }   # This DOES NOT render/execute the file. Why?
    end
  end

end

视图/共享/whatever.js.erb

  # js code that executes 

routes.rb

  concern :socionics_votes do
    member do
      post 'vote_socionics'
    end
  end

  resources :universes
  resources :characters,  concerns: :socionics_votes
  resources :celebrities, concerns: :socionics_votes
  resources :users,       concerns: :socionics_votes

推荐答案

module SocionicsVotesConcern
  extend ActiveSupport::Concern

  included do 

    def vote_socionics
      respond_to do |format|
        format.js { render 'shared/vote_socionics' }
      end      
    end

  end

end

将在关注中定义的所有操作/方法包装在included do块中.这样,该块中的任何内容都将被视为直接写入includer对象(即您要将其混入其中的控制器)

Wrap any actions/methods you define in the concern in an included do block. This way, anything in the block will be considered as if it was directly written in the includer object (i.e. the controller you're mixing this into)

使用此解决方案,不会出现松散的结局,没有特质,也不会偏离滑轨模式.您将可以使用respond_to块,而不必处理奇怪的东西.

With this solution, there are no loose ends, no idiosyncracies, no deviations from rails patterns. You will be able to use respond_to blocks, and won't have to deal with weird stuff.

这篇关于如何从控制器中包含的模块渲染js模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆