ruby-on-rails - 为什么 Rails 不自动创建连接表条目?

标签 ruby-on-rails activerecord

我有一个简单的 has_many 通过关系设置:

class Tag < ActiveRecord::Base
  has_many :profile_tags
  has_many :profiles, :through => :profile_tags
end

class ProfileTags < ActiveRecord::Base
  belongs_to :profile
  belongs_to :tag
end

class Profile < ActiveRecord::Base
  has_many :profile_tags
  has_many :tags, :through => :profile_tags
end

在我看来,我正在接受一组标签(只是字符串),并在我的 Controller 中迭代它们并在每个标签上调用 Tag.create( ... ),并将它们插入一个数组。这一切都很好。

所以我得到了一个点,我有一个 Tag 对象(标签)数组,每个对象都由创建调用返回,还有变量@profile,它是通过执行 Profile.new 创建的

我想这样做:@profile.tags = tags

这样做会在我尝试赋值的那一行导致这个错误:

uninitialized constant Profile::ProfileTag

Rails 就像我需要手动创建和分配连接表关联一样,即使这里是 http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association它指出,当您执行这样的任务时,将创建新的关联,如果一些关联消失,它们将被删除。

知道我在这里做错了什么吗?

最佳答案

Rails 假定模型类以单数形式命名,即类 ProfileTags 应称为 ProfileTag

根据您使用的 Rails 版本,解决此问题的最简单方法可能是在 Rails 中使用 script/destroyscript/generate 重新创建模型2.x 或 Rails 3 中的 rails destroyrails generate

或者,通过将 :class_name => 'ProfileTags' 添加到 has_many 声明来手动指定类名也应该有效。

关于ruby-on-rails - 为什么 Rails 不自动创建连接表条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3692183/

相关文章:

ruby-on-rails - 函数中的puts语句未执行,函数测试失败,但收到(:function) spec works

activerecord - 如何将 'IN (1,2,3)' 与 findAll 一起使用?

ruby-on-rails - 如何将 activerecord-sqlserver-adapter 与 TinyTDS *和* Windows 上的集成安全连接一起使用 *无需*以纯文本形式保存密码

ruby-on-rails - 我可以在 after_commit(在 : :create) callback? 上)更新 Active Record

ruby-on-rails - 显示配置文件名称而不是配置文件 ID

ruby-on-rails - Rails Redis 排行榜

ruby-on-rails - ruby 'Could not load OpenSSL' 错误 macOS Sierra

ios - 我如何知道用户是否收到了 privatepub gem 发送的推送通知

javascript - 输入 javascript 验证仅在最后一个有效

ruby-on-rails - ActiveRecord虚拟属性作为记录属性