使用主键从数据库中的第三个模型中检索数据

时间:2014-05-28 05:47:31

标签: ruby-on-rails database primary-key jointable

我想通过使用下面架构中的主键来访问当前用户的相册。我有User,Band和Album模型如下......

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_many :bands
end

class Band < ActiveRecord::Base
  has_many :albums
  has_many :users
end

class Album < ActiveRecord::Base
  belongs_to :band
end

架构如下......

create_table "albums", force: true do |t|
  t.string   "name"
  t.string   "releaseDate"
  t.string   "artWorkUrl"
  t.integer  "band_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "bands", force: true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "user_id"
end

create_table "users", force: true do |t|
  t.string   "email",                  default: "", null: false
  t.string   "encrypted_password",     default: "", null: false
  t.string   "reset_password_token"
  t.datetime "reset_password_sent_at"
  t.datetime "remember_created_at"
  t.integer  "sign_in_count",          default: 0,  null: false
  t.datetime "current_sign_in_at"
  t.datetime "last_sign_in_at"
  t.string   "current_sign_in_ip"
  t.string   "last_sign_in_ip"
  t.datetime "created_at"
  t.datetime "updated_at"
end

我正在尝试在相册控制器中使用以下方法...

def albums
  @albums = current_user.bands.albums
end

对不起,我确定这是一个菜鸟问题。我知道这应该是通过用户进行的简单主键访问 - &gt;乐队 - &gt;专辑,使用user_id和band_id,但无法通过乐队填充当前用户专辑。非常感谢任何见解。

3 个答案:

答案 0 :(得分:1)

def albums
  band_ids = current_user.bands.map(&:id)
  @albums = Album.where(band_id: band_ids)
end

通过分隔查询,您没有n+1 problemWhat is SELECT N+1?

答案 1 :(得分:1)

  

使用主键

当您引用同一个表时,您应该查看foreign_keysprimary_keys。那么您真正要求的应该是如何为我的模型正确设置Rails关联?

以下是:

#app/models/user.rb
Class User < ActiveRecord::Base
   has_many :bands
end

#app/models/band.rb
Class Band < ActiveRecord::Base
    has_many :albums
    belongs_to :user
end

#app/models/album.rb
Class Album < ActiveRecord::Base
    belongs_to :band
end

这样您就可以拨打current_user.bands.first.albums

-

备注

您必须记住bands关联将是collection。这意味着您无法拨打....bands.albums。相反,您需要像这样遍历数组:

<% for band in current_user.bands do %>
   <%= band.albums.inspect %>
<% end %>

答案 2 :(得分:0)

在用户类中定义另一个关联

class User < ActiveRecord::Base    
  has_many :albums, :through => bands
end

在您的控制器中

@albums = current_user.albums