product.number for user_id rails
I have a question for rails.
I have a User controller, I have a Product controller.
I have a user id references in product:db.
How to puts User.product number in Html?
Firstly you need configure devise gem for authentication to your user model to add user_id column to your products table.
rails g migartion add_user_id_to_products user_id:integer:index
In your users model
class User < ApplicationRecord has_many :products end
In your products model
class Products < ApplicationRecord belongs_to :user end
As your user and products are associated through has_many and belongs_to. you can as below in the products controller
class ProductsController < ApplicationController def index @products = Product.all end def new @product = Product.new end def create @product = current_user.products.build(product_params) if @product.save redirect_to edit_product_path(@product), notice: "Saved..." else render :new end end private def product_params params.require(:product).permit( :title, :description, :category) end end
If the data is successfully saved into the database, you will find the user_id column of the products table filled with the id of the current_user.
To get all the products of a particular user
In your users controller show action
def show @user_products = @user.products end
The @user_products will have all the products belonging to the corresponding user.