3

我在控制器问题中有一个动作,它包含在控制器中。此操作不会呈现在 respond_to 块下指定的 js.erb 文件。如何在控制器关注点中正确获取操作以成功呈现 js.erb 文件(或任何视图,就此而言)?我的路线有问题吗?

模块操作的链接

= 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

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

= link_to "whatever", characters_whatever_path, remote: true

控制器/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 

路线.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
4

2 回答 2

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

有了这个解决方案,就没有松散的结局,没有特质,也没有偏离轨道模式。您将能够使用respond_to积木,而不必处理奇怪的东西。

于 2014-07-20T01:38:33.657 回答
1

我不认为这是兼容 Rails 的人。

  • 控制器动作呈现视图或重定向;
  • 一个模块有方法。方法执行代码;

因此,仅包含名为控制器的模块中的方法是行不通的。你真正需要做的是从控制器 A 调用一个动作到控制器 B。所以SocionicsVotesController会变成一个真正的控制器类,你会使用redirect_to rails 方法。

您必须指定要重定向到的控制器和操作,例如:

redirect_to :controller => 'socionics', :action => 'index'

要不就:

redirect_to socionics_url

默认情况下,它将发送一个HTTP 302 FOUND

编辑:

如果您想重用控制器操作的响应方式,同时使用 rails 4 关注点,请尝试以下操作:

class CharactersController < ApplicationController
  include SocionicsVotesControllerConcerns  # not actually a controller, just a module.

  def an_action
    respond
  end


module SocionicsVoteControllerConcerns
    extend ActiveSupport::Concern

    def respond
      respond_to do |format|
        format.html { render 'whatever' }
        format.json { head :no_content }
      end
    end
end

我只是在将 format.js 更改为 format.html 时才让它工作,可能是因为这个

于 2014-07-16T06:40:50.413 回答