gpt4 book ai didi

ruby-on-rails - 帮助 HABTM :through

转载 作者:行者123 更新时间:2023-12-03 15:30:02 25 4
gpt4 key购买 nike

到目前为止,我当前的 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/

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