与现有 Rails 4 个应用程序友好:无变化

Friendly with existing Rails 4 app: No change

我有一个设计 运行 的现有应用程序。用户和登录和注销等。以为我想让 localhost:3000/users/15 更改为 localhost:3000/users/ruby-boy 所以我安装了 https://github.com/norman/friendly_id

我有 运行 rails generate friendly_id 但是当我 运行 rails generate scaffold user name:string slug:string:uniq 时,它说我已经有一个 user.rb 文件所以好的我添加了: rails g migration AddSlugToUser slug:string:uniqrails g migration AddNameToUser name:string。所以我将这两列添加到我的用户 table.

在我的控制器中,我更换了:

User.find(params[:id])

与:

User.friendly.find(params[:id])

然后 运行 这个在控制台中 (rails c)

User.find_each(&:save)

但是User.find_each(&:save)给出了:

 (0.1ms)  commit transaction
 (0.0ms)  begin transaction
 => nil

我想我已经遵循了文档 "eye for eye"。我错过了什么吗,因为链接不会改变。

PS:我在 github 上编辑了每个网站的 user.rb。

我的user.rb:

class User < ActiveRecord::Base
       extend FriendlyId
      friendly_id :name, use: :slugged
      # Include default devise modules. Others available are:
      # :confirmable, :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable
      belongs_to :plan
      has_one :profile

      attr_accessor :stripe_card_token

      def save_with_payment
        if valid?
            customer = Stripe::Customer.create(description: email, plan: plan_id, card: stripe_card_token)
            self.stripe_customer_token = customer.id
            save!
        end
      end
    end

用户架构 table:

create_table "users", force: :cascade do |t|
      t.string   "email",                  default: "", null: false
      t.string   "encrypted_password",     default: "", null: false
      t.string   "reset_password_token"
      t.datetime "reset_password_sent_at"
      t.datetime "remember_created_at"
      t.integer  "sign_in_count",          default: 0,  null: false
      t.datetime "current_sign_in_at"
      t.datetime "last_sign_in_at"
      t.string   "current_sign_in_ip"
      t.string   "last_sign_in_ip"
      t.datetime "created_at"
      t.datetime "updated_at"
      t.integer  "plan_id"
      t.string   "stripe_customer_token"
      t.string   "slug"
      t.string   "name"
    end

:name 添加到您的注册表单,然后在您的用户模型中验证唯一性

Class User
  validates :name, uniqueness: true

这样就不会多次创建相同的名称,这样您就可以避免出现奇怪的 slug。