【问题标题】:Trying to call a method and redirect after尝试调用方法并在之后重定向
【发布时间】:2015-10-19 18:41:41
【问题描述】:

我正在尝试调用此 post 方法,然后重定向到链接所在的位置,但我被路由绊倒了。该方法被调用,但仅此而已。我做错了什么?

<%= link_to image_tag('notifications3.fw.png', size: "32x32", title: "Notifications", class: 'cr'), activities_path %>

我的路线

resources :activities, path: 'notifications'
post 'activities/read_all_notifications'

js

    $(document).on('click', '.cr', function(e) {
      e.preventDefault();
      return $.ajax('/activities/read_all_notifications', {
        type: "post",
        dataType: "json",
        beforeSend: function(xhr) {
          return xhr.setRequestHeader("X-CSRF-Token", $("meta[name=\"csrf-token\"]").attr("content"));
        },
        cache: false
      });
    });

方法

def index
    @activities = PublicActivity::Activity.order(created_at: :desc)
                                .where(recipient_id: current_user.id, 
                                recipient_type: 'User')
end

def read_all_notifications
    PublicActivity::Activity.where(recipient_id: current_user.id).update_all(:read => true)
    render nothing: true
end 

日志

    Started POST "/activities/read_all_notifications" for 127.0.0.1 at 2015-10-19 11:55:51 -0700
    Processing by ActivitiesController#read_all_notifications as JSON
      User Load (1.0ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 3 LIMIT 1
      SQL (1.5ms)  UPDATE "activities" SET "read" = 't' WHERE "activities"."recipient_id" = 3
      Rendered text template (1.5ms)
    Completed 200 OK in 28ms (Views: 3.5ms | ActiveRecord: 2.5ms)

【问题讨论】:

  • 你怎么知道方法被调用了?
  • 它显示在日志中。
  • 您正在进行 AJAX 调用,因此如果您需要执行任何重定向,则由该 JavaScript 代码负责。 Rails 级别的重定向将被忽略。为什么不render(json: { redirect: '/...' }) 并返回目标目的地,然后让 JavaScript 接收并相应地重定向?
  • 如果要重定向,为什么要使用ajax?
  • 抱歉,还是新手。我希望链接转到一页,但在此之前只需调用 read_all_notifications

标签: ruby-on-rails ruby ruby-on-rails-4 routing


【解决方案1】:

如何将链接更改为

<%= link_to image_tag('notifications3.fw.png', size: "32x32", title: "Notifications", class: 'cr'), 'activities/read_all_notifications', method: :post %> 

并在 html 中处理它(删除 javascript)

# And in the controller 

def read_all_notifications
  PublicActivity::Activity.where(recipient_id: current_user.id).update_all(:read => true)
  redirect_to :activities
end 

注意,您可以将路线更改为

resources :activities, path: 'notifications' do
  collection do 
     post :read_all
  end
end

然后,在视图中,您可以使用方法(read_all_notifications_path)生成 url。从长远来看,这更加灵活和更好。

<%= link_to image_tag('notifications3.fw.png', size: "32x32", title: "Notifications", class: 'cr'), read_all_notifications_path, method: :post %> 

【讨论】:

  • read_all 路由是否应该为 read_all_notifications 以匹配操作?
  • 另外,现在它会渲染通知页面两次
  • 如果您这样做,该操作将更改为“read_all”。方法是read_all_activities_path。您可以随时使用rake routes 查看路线。此外,您可以向路由添加:as =&gt; :notifications 属性,并将它们作为通知在任何地方引用。然后read_all_notifications_path 就可以了。
猜你喜欢
  • 1970-01-01
  • 2019-04-13
  • 2018-12-07
  • 1970-01-01
  • 2023-04-08
  • 2017-05-07
  • 2017-10-28
  • 2019-04-05
  • 1970-01-01
相关资源
最近更新 更多