开发者

Rails 3 validations and non REST URLs

开发者 https://www.devze.com 2023-02-21 12:06 出处:网络
I have a route setup like this: match \'/:url\' => \'subjects#show\' In my Subjects controller I use

I have a route setup like this:

match '/:url' => 'subjects#show'

In my Subjects controller I use

@subject = Subject.where("url = ?", params[:url].downcase).first 

instead of

@subject = Subject.find(params[:id])

and this works just fine. The problem is that none of my validation work for the Subject model.

validates :url, :uniqueness => true

This above validation does not work and I get this but only when the url already exists:

SQL (0.5ms)  BEGIN
  Subject Load (0.3ms)  SELECT `subjects`.`id` FROM `subjects` WHERE (`subjects`.`url` = BINARY '78') LIMIT 1
  SQL (0.2ms)  ROLLBACK
  SQL (0.2ms)  BEGIN
  CACHE (0.1ms)  SELECT `subjects`.`id` FROM `subjects` WHERE (`subjects`.`url` = BINARY '78') LIMIT 1
  SQL (0.1ms)  ROLLBACK

I get forwarded to the existing record's subjects/show as if everything's great. Otherwise, when the url is unique, the exact same SQL query does not get rolled back and the record is created.

Any ideas how I should tackle this? Is this related to my custom subject routes? I'm pulling my hair out. Here's the rest of my routes:

  match '/auth/:provider/callback' => 'authentications#create'
  mat开发者_Python百科ch '/about' => 'pages#about'
  match '/dashboard' => 'subjects#index', :as => 'user_root'

  get "pages/home"
  get "pages/about"

  resources :authentications

  devise_for :admins
  devise_for :users, :controllers => {:registrations => 'registrations'} 

  resources :subjects do
    member do
      get 'stats'
      get 'comments'
      get 'qrcode'
      get 'download_qrcode'
    end
  end

  resources :traits
  resources :ratings
  resources :assets 

  match '/:url/stats' => 'subjects#stats'
  match '/:url/remove' => 'subjects#remove'
  match '/:url/comments' => 'subjects#comments'
  match '/:url/edit' => 'subjects#edit'
  match '/:url' => 'subjects#show'

  root :to => "pages#home"


I think your routes file is OK.

Usually ActiveRecord rollback selects when you already have duplicated entries in your table, like multiple null or blank entries. If you set the uniqueness validation after populate the table and you don't set an index into your migration file, probably that's the problem.

In this case, you can do:

  • Insert index into your migration file:

    class CreateSubjects < ActiveRecord::Migration
      def change
        ...
      end
      add_index :subjects, :url, :unique => true
    end
    
  • Redo migrations and seed the table.

If this doesn't work, please send your migration file and active_record model.

0

精彩评论

暂无评论...
验证码 换一张
取 消