【问题标题】:How to set associations using namespaces and SQL tables with different names from those of Ruby on Rails models?如何使用与 Ruby on Rails 模型名称不同的名称空间和 SQL 表来设置关联?
【发布时间】:2011-06-19 06:05:05
【问题描述】:

我正在使用 Ruby on Rails 3 和 SQL 数据库。我正在尝试重命名数据库表,以达到 RoR 模型和 SQL 表之间的“名称和谐”。


例如...

... 在 'RAILS_ROOT/config/routes.rb' 我有这个:

namespace "users" do
  resources :accounts
end

namespace "second" do
  resources :profiles
end

...在 'RAILS_ROOT/models/account.rb' 我有这个:

has_one :profile,
  :class_name => "Second::Profile"

...在 'RAILS_ROOT/models/profile.rb' 我有这个:

belongs_to :account

.. 在 SQL 数据库中,我有名为:

accounts
profiles  

我想继续使用语法

Users::Account.find(1)

在我的 RoR 应用程序中,但我希望我的 SQL 表名称如下:

users_accounts
second_profiles

怎么做?

P.S.:我阅读了 ActiveRecord::Base "table_name()" 和 "table_name_prefix" 部分,但我无法设置这些部分。

【问题讨论】:

    标签: ruby-on-rails ruby database ruby-on-rails-3 namespaces


    【解决方案1】:

    在您的模型中使用以下代码:

    class User
      set_table_name "users_accounts"
    end
    
    class Profile
      set_table_name "second_profiles"
    end
    

    希望对你有帮助。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多