当我转到字符控制器时,显示动作,所有正常的参数:id是它应该如何根据REST。
在显示视图中,我呈现了一个部分。在这个部分中,我有一个指向vote_socionics操作的链接。此操作在socionics_votes模块下定义,该模块由字符控制器包含。(我以这种方式设置它,因为我有其他控制器,其中也包括这个模块)。
我的问题是,当我单击此链接并将其转到socionics_votes_module.rb文件中的socionics_votes_module.rb私有方法时,params[:id]就不再存在。使用pry,我发现它实际上变成了params[:character_id]
问题:
1)为什么会发生这种情况(这是因为它属于“不同的”控制器,即使它是一个模块?)
2)我该如何解决这个问题?我认为使用params:id会更优雅,而不必做if- for来解释这两个键。
characters_controller.rb
class CharactersController < ApplicationController
include SocionicsVotesModule
def show
@character = Character.find(params[:id])
endcharacters/show.html.haml
= render partial: 'votes/vote_socionics',
locals: { votable: @votable, votable_name: @votable_name, socionics: @socionics }_vote_socionics.html.haml
= link_to content_tag(:div,"a"), send("#{votable_name}_vote_socionics_path", votable, vote_type: "#{s.type_two_im_raw}"),
id: "vote-#{s.type_two_im_raw}",
class: "#{current_user.voted_on?(votable) ? 'voted' : 'not-voted'}",
method: :post,
data: { id: "#{s.type_two_im_raw}" } socionics_votes_module.rb
module SocionicsVotesController
extend ActiveSupport::Concern
included do
before_action :set_votable
end
private
def set_votable
votable_constant = controller_name.singularize.camelize.constantize
@votable = votable_constant.find(params[:id]) # This is where it fails, since there is no params[:id], and rather, params[:character_id]
end
def set_votable_name
@votable_name = controller_name.singularize.downcase
endroutes.rb
concern :socionics_votes do
post 'vote_socionics'
end
resources :characters, concerns: :socionics_votes
resources :celebrities, concerns: :socionics_votes
resources :users, concerns: :socionics_votes当部分悬停时,部分链接的URL。
localhost..../characters/4-cc/vote_socionics?vote_type=neti
像.find(params[:id] || params[:"#{@votable_name}_id"])这样的东西没有起作用,而且看上去很傻。
发布于 2014-07-03 11:13:22
您需要将vote_socionics路由添加为资源的成员:
concern :socionics_votes do
member do
post 'vote_socionics'
end
end这样就可以正确地设置id参数。
https://stackoverflow.com/questions/24550398
复制相似问题