ruby-on-rails - 如何从 Controller 中包含的模块渲染js模板?

标签 ruby-on-rails templates module actioncontroller respond-to

我在 Controller 关注点中有一个 Action ,它被包含在一个 Controller 中。此操作不会呈现 respond_to block 下指定的 js.erb 文件。 如何在 Controller 关注点中正确执行操作以成功呈现 js.erb 文件(或任何 View ,就此而言)?我的路由有问题吗?

模块操作的链接

= 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

** Controller 操作的链接**

= 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

controllers/concerns/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

views/shared/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 block 中。这样, block 中的任何内容都将被视为直接写入包含器对象(即您将其混合到其中的 Controller )

有了这个解决方案,就没有松懈、没有特质、没有偏离 rails 模式。您将能够使用 respond_to block ,而不必处理奇怪的东西。

关于ruby-on-rails - 如何从 Controller 中包含的模块渲染js模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24772898/

相关文章:

ruby-on-rails - Rails 4.2 片段缓存不起作用

ruby-on-rails - Rails 的 PayPal 小额支付

c++ - 演绎指南是否需要 noexcept 说明符?

c++ - MSVC 2010 模板编译器问题

c# - System.IO.FileNotFoundException 未处理消息 =“The specified module could not be found. (Exception from HRESULT: 0x8007007E)”

module - 如何在 Racket 模块中查找所有功能的列表?

ruby-on-rails - 设计从 1.1.5 升级到 1.4.5 会导致错误数量的参数错误

ruby-on-rails - simple_form 的 Rails 表单关联

c++ - 没有宏的模板特化类型列表?

javascript - 如何使用 Browserify 导出对象?