Rails friendly_id gem for pretty url

时间:2014-07-19 22:15:14

标签: ruby-on-rails ruby devise friendly-id

有没有办法使friendly_id动态,如下所示,所以根据我的用户模型中的属性(next_language),我可以调整网址的外观。我正在使用设计。理想情况下,我希望控制器能够处理这种逻辑,但却无法想到如何做到这一点。以下错误因为lang模型不知道current_user。

lang model:

class Lang < ActiveRecord::Base

   if current_user.next_language == "English"
    extend FriendlyId
    friendly_id :english
   end

   if current_user.next_language == "Spanish"
    extend FriendlyId
    friendly_id :spanish
   end

end

这是有人注册时生成的示例用户记录:

User.find(5)
  User Load (0.9ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 5]]
 => #<User id: 5, email: "mtcrts71@gmail.com", encrypted_password: "$2a$10$ZRBXllLt7lmU7YUuCV62.OzlaaleE/XnV4yzQwJtSN9f...", confirmation_token: nil, confirmed_at: "2014-07-19 17:48:29", confirmation_sent_at: "2014-07-19 17:46:15", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2014-07-19 17:48:29", last_sign_in_at: "2014-07-19 17:48:29", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2014-07-19 17:46:15", updated_at: "2014-07-19 17:48:29", next_language: "English", admin: false, unconfirmed_email: nil, bookmark: 1, bookmark2: 0, qscore: 0, quiz_flag: 0, total_quiz: 0, natives_language: "Spanish", fqscore: nil>

示例lang记录:

Lang.find(1)
  Lang Load (0.8ms)  SELECT "langs".* FROM "langs" WHERE "langs"."id" = $1 LIMIT 1  [["id", 1]]
 => #<Lang id: 1, english: "be", english_to_spanish: "ser", spanish: "una", spanish_to_english: "a", created_at: "2014-07-11 01:30:53", updated_at: "2014-07-11 01:30:53"> 

基于以上所述,如果用户正在学习西班牙语,则网址可能如下所示:

http://localhost:3000/langs/una

或英语:

http://localhost:3000/langs/be

编辑以包含控制器和视图代码:

控制器:

class StaticPagesController < ApplicationController

  def home
    if user_signed_in?
      @placemark = Lang.find(current_user.bookmark)
    end
  end
end

相关观点代码:

<%= link_to "Continue Learning!", lang_path(@placemark), class: "btn btn-large btn-primary"%>

1 个答案:

答案 0 :(得分:2)

根据文档,这应该有效:

class Lang < ActiveRecord::Base
  extend FriendlyId
  friendly_id :determine_slug

private
  def determine_slug
    case current_user.next_language
    when 'English' then :english
    when 'Spanish' then :spanish
  end

  def current_user
    Thread.current[:current_user]
  end
end

了解如何将current_user存储在Thread.current此处:Safety of Thread.current[] usage in rails并注意权衡。