ruby-on-rails - 帮助 HABTM :through

标签 ruby-on-rails

到目前为止,我当前的 HABTM 实现与 :has_and_belongs_to_many 一起工作。 Notification 和 Privacy 都继承自 Preference。偏好是 STI。我想尝试使用 :has_many, :through 关联。

模型文件

class User < ActiveRecord::Base
  has_and_belongs_to_many :preferences
end

class Preference < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class Notification < Preference
end

class Privacy < Preference
end

迁移文件

class UsersHaveAndBelongToManyPreferences < ActiveRecord::Migration
  def self.up
    create_table :preferences_users, :id => false do |t|
      t.references :preference, :user

      t.timestamps
    end
  end

  def self.down
    drop_table :preferences_users
  end
end

class CreatePreferences < ActiveRecord::Migration
  def self.up
    create_table :preferences do |t|
      t.string :title
      t.text :description
      t.string :type

      t.timestamps
    end
  end

  def self.down
    drop_table :preferences
  end
end

class DeviseCreateUsers < ActiveRecord::Migration
  def self.up
    create_table(:users) do |t|
      t.string :name
      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end

我尝试了以下

class User < ActiveRecord::Base
  has_many :preferences, :through => :preferences_users
end

class Preference < ActiveRecord::Base
  has_many :users, :through => :preferences_users
end

我的表格看起来像

  <% Preference.where(:type => 'Notification').all.each do |notification| %>
    <li>
      <%= check_box_tag 'user[preference_ids][]', notification.id, @user.preference_ids.blank? ? false : @user.preferences.include?(notification) %>
      <%= label_tag notification.description %>
    </li>
  <% end %>

我明白了

Could not find the association :preferences_users in model User

我做错了什么?问题出在我的表格还是我的联想?

最佳答案

好的,它开始工作了。我需要一个模型 PreferencesUser,但在用户和偏好模型上缺少 has_many :preferences_users:

class PreferencesUser < ActiveRecord::Base
    belongs_to :user
    belongs_to :preference
end

class User < ActiveRecord::Base
  has_many :preferences_users
  has_many :preferences, :through => :preferences_users
end

class Preference < ActiveRecord::Base
  has_many :preferences_users
  has_many :users, :through => :preferences_users
end

不必更改我的表单中的任何内容。希望这对某人有帮助

关于ruby-on-rails - 帮助 HABTM :through,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4545735/

相关文章:

ruby-on-rails - ruby on rails 网站上的 "blog tutorial"视频有多过时?

ruby-on-rails - Rails 路由中的变量

ruby-on-rails - Rails 按关联模型排序

ruby-on-rails - 对于管理整个学区的大型系统,关系数据库还是非关系数据库?

ruby-on-rails - Carrierwave - "uploading"来自字符串的文件

ruby-on-rails - 服务对象的 Rails 名称约定

ruby-on-rails - Rails .save() 不存储 Id

sql - 获取关联记录时如何减少 Ruby on Rails 3 中的 SQL 查询数量

javascript - 无法使用 Watir 从特定网页抓取数据

ruby-on-rails - 有没有像 cacti 一样使用 Rails 的开源项目?