我有一个类似reddit的应用,允许用户投票选择Activerecord Reputation System gem的链接。
我正在尝试创建基于Railscast#199的移动版本,如果通过移动设备访问该网站,则会使用mobile.erb
格式。
投票方法在非移动格式下工作正常(默认为javascript,但也适用于html),但在移动设备中返回错误,如下所示。请注意,它正在尝试Get
而不是Post
。
Started GET "/links/98/vote?type=like" for 127.0.0.1 at 2012-12-25 19:16:45 -0500
ActionController::RoutingError (No route matches [GET] "/links/98/vote"):
可能导致这种情况的原因是什么? before_filter
阻止了javascript吗?我怎样才能解决这个问题?非常感谢您的投入!
application_controller.rb
before_filter :prepare_for_mobile
def prepare_for_mobile
session[:mobile_param] = params[:mobile] if params[:mobile]
request.format = :mobile if mobile_device?
end
def mobile_device?
if session[:mobile_param]
session[:mobile_param] == "1"
else
request.user_agent =~ /Mobile/
end
end
helper_method :mobile_device?
的routes.rb
resources :links do
member { post :vote }
end
links_controller.rb
def vote
value = params[:type] == "like" ? 1 : 0
@link = Link.find(params[:id])
@link.add_or_update_evaluation(:link_votes, value, current_user)
respond_to do |format|
format.html { redirect_to :back }
format.mobile { redirect_to :back }
format.js
end
end
_link.mobile.erb
<div id="link_<%= @link.id %>">
<%= link_to "like", vote_link_path(@link, type: "like"), method: "post", remote: true %>
</div>
<div id="link_points_<%= @link.id %>">
<%= @link.reputation_for(:link_votes).to_i %>
</div>
vote.js.erb
$('#link_<%= @link.id %>').html("<%= j link_to "up", vote_link_path(@link, type: "like"), method: "post", remote: true %>");
$('#link_points_<%= @link.id %>').html("<%= @link.reputation_for(:link_votes).to_i %>;
答案 0 :(得分:0)
这就是我的所作所为:
<强>配置/初始化/ mime_types.rb 强>
Mime::Type.register_alias "text/html", :mobile
Mime::Type.register_alias "text/javascript", :mobilejs /* newly added mobilejs */
<强> application_controller.rb 强>
before_filter :prepare_for_mobile
def prepare_for_mobile
session[:mobile_param] = params[:mobile] if params[:mobile]
if mobile_device?
if request.format == :js
request.format = :mobilejs /* newly added mobilejs format */
else
request.format = :mobile
end
end
end