开发者

Rails 3 ActiveRecord Table Name Issue

开发者 https://www.devze.com 2023-04-12 23:58 出处:网络
I\'m on Windows XP... Ruby 1.9.2 Rails 3.0.9 MS SQL Server 2005 I\'m using tiny_tds + activerecord-sqlserver-adapter

I'm on Windows XP...

Ruby 1.9.2

Rails 3.0.9

MS SQL Server 2005

I'm using tiny_tds + activerecord-sqlserver-adapter

In my database I have table named t4. I have created a model like this: rails generate model t4 Here is my simple model t4.rb:

class T4 < ActiveRecord::Base
end

Here is migration file 20111013125957_create_t4s.rb:

class CreateT4s < ActiveRecord::Migration
 def self.up

 create_table :t4s do |t|
  t.timestamps
 end
end

def self.down
  drop_table :t4s
end

end

I have schema.rb:

...
create_table "t4", :force => true do |t|
  t.string "title", :limit => 50
end
...

Problem: When I try T4.select("title").where(["id = 3"]) I get error message: ActiveRecord::StatementInvalid: TinyTds::Error: Invalid object name 't4s'.: SELECT title FROM [t4s] WHERE (id = 3)

P.S.: I have another so开发者_JAVA技巧me tables named Adddocs and Eclaims. There are not problems with queries to them.

I guess that problem is that T4.select("title").where(["id = 3"]) maps to SELECT title FROM [t4s] WHERE (id = 3) (T4 to t4s). Why? I don't know

But when I edited file config/initializers/inflections.rb like this:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 't4', 't4'
end

Everything works! But it's not suitable solution (bad tone i think) :(((


By convention, if you create a model named album, rails will create a table called albums.

To override this (which isn't usually done) and use a custom defined table name you can use set_table_name method like this in your model:

  class Album < ActiveRecord::Base
      self.table_name="album" * define here whatever table name you have
    end


When you create a new model it is the singular of the object your storing, whereas when it then generates the table, it uses the plural as there are multiple stored within the table. Example...

If you create a model named user, you'll end up with app/models/user.rb but the table it makes will be called users.

If you don't like that you have a few options...

  • You can override the inflections as you've done, however you should only do this if Rails is getting the pluralization wrong, rather than forcing it to use a certain word.

  • You can override the table name using the set_table_name method in the model file, providing it with a parameter of what your table name actually is.

  • You could disable the whole pluralized table names with config.active_record.pluralize_table_names = false in your config/application.rb file, however I strongly recommend you don't do this.

Ultimately I would suggest using more descriptive table names which can be pluralized over ones that can't. T4 as a model and table name don't explain to me what's stored within, where as Post does.

0

精彩评论

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