How can I link two database tables together
I'm not too sure how else to word this question, as I can't find anything on google about it.
Basically, I have a user and they create products. This is the schema:
create_table "users", force: :cascade do |t|
t.string "email"
t.string "username"
t.string "encrypted_password"
t.string "description"
t.string "address"
t.string "phone_number"
end
create_table "products", force: :cascade do |t|
t.string "name", default: "", null: false
t.string "description"
t.string "quantity"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
What I want to do is something like this:
@products.users.username
So I can associate the user with a product they have created. My model is as followed:
class User < ActiveRecord::Base
has_many :products
end
class Product < ActiveRecord::Base
belongs_to :user
end
And for my product controller, namely for show.html.erb:
def show
@products = Product.find(params[:id])
end
Basically, when you're on the show.html.erb page, you can click the product and it loads the product's information page, and I want the product information page to list the user who created the product. I thought something like this would work:
@products.user.username
However, it tells me "undefined username", and I have a feeling there is something I have missed. Currently, when a product is created, the product is associated with a user id.
Thank you for your help.
Posted Dec 16, 2018, 11:50 PM UTC