2

我有一个类似 reddit 的应用程序,它允许用户使用Activerecord Reputation System gem为链接投票。

我正在尝试创建一个基于Railscast#199mobile.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?

路线.rb

resources :links do
  member { post :vote }
end

链接控制器.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>

投票.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 %>;
4

1 回答 1

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
于 2012-12-27T14:25:59.430 回答