gpt4 book ai didi

ruby-on-rails - 如何使用与 Ruby on Rails 模型名称不同的 namespace 和 SQL 表设置关联?

转载 作者:行者123 更新时间:2023-12-04 17:00:50 26 4
gpt4 key购买 nike

我正在使用 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”部分,但我无法设置它们。

最佳答案

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

class User
set_table_name "users_accounts"
end

class Profile
set_table_name "second_profiles"
end

我希望它有帮助。

关于ruby-on-rails - 如何使用与 Ruby on Rails 模型名称不同的 namespace 和 SQL 表设置关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4862568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com