我在 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/