在Rails中,如何从Active Record左连接表中打印出user.name

时间:2015-10-01 00:05:14

标签: ruby-on-rails ruby activerecord

我有用户和相册表。 “相册”表的外键是user_id

我的Active Record查询是:

def show
  @album = Album.find(params[:id])
  @added_by = User.joins('LEFT OUTER JOIN albums ON albums.id = (params[:id])')
end

在我的再培训局中,我有:

<%= added_by.name %>

我的架构是:

ActiveRecord::Schema.define(version: 20150930203820) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "albums", force: :cascade do |t|
    t.string   "artist",     null: false
    t.integer  "year"
    t.string   "title",      null: false
    t.string   "pressing"
    t.string   "format"
    t.string   "label"
    t.string   "genre"
    t.text     "image_url"
    t.string   "tracklist"
    t.string   "country"
    t.text     "comment"
    t.boolean  "favorite"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
  end

  add_index "albums", ["user_id"], name: "index_albums_on_user_id", using: :btree

  create_table "users", force: :cascade do |t|
    t.string   "email",                      null: false
    t.string   "pic_url"
    t.string   "name",                       null: false
    t.string   "favorite"
    t.string   "crypted_password"
    t.string   "salt"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.datetime "last_login_at"
    t.datetime "last_logout_at"
    t.datetime "last_activity_at"
    t.string   "last_login_from_ip_address"
  end

  add_index "users", ["last_logout_at", "last_activity_at"], name: "index_users_on_last_logout_at_and_last_activity_at", using: :btree
  add_index "users", ["name", "email"], name: "index_users_on_name_and_email", unique: true, using: :btree

  add_foreign_key "albums", "users"
end  

1 个答案:

答案 0 :(得分:0)

只需尝试:

@album.user.name

如果现在有效,那么确保您已在以下模型中设置 Active Record Associations

# user.rb
class User < ActiveRecord::Base
  has_many :albums
end
# album.rb
class Album < ActiveRecord::Base
  belongs_to :user
end