ruby - In Rails, how do I print out a user.name from an Active Record left join table -
i have users , albums tables. foreign key albums table user_id.
my active record query is:
def show @album = album.find(params[:id]) @added_by = user.joins('left outer join albums on albums.id = (params[:id])') end in erb have:
<%= added_by.name %> my schema is:
activerecord::schema.define(version: 20150930203820) # these extensions must enabled in order support database enable_extension "plpgsql" create_table "albums", force: :cascade |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 |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
simply try:
@album.user.name if work make sure have set active record associations in models like:
# user.rb class user < activerecord::base has_many :albums end # album.rb class album < activerecord::base belongs_to :user end
Comments
Post a Comment