So i have 2 models Users and books. Books has user_id,name, User has name,adress. Both have views. I did create a link_to in user view to redirect to books view, but i want to redirect by id.
What i mean if i click in User1 link_to, i want to view only user1 books(books that have only user_id:1 if it is possible to see the most recent created at the beginning, so if i have created book.id=5 would get first and book.id=1 would be lastone).
User model:
Class User < ApplicationRecord
has_many :books
Book Model:
Class Book < ApplicationRecord
belongs_to :user
Controller book show:
def show
@book = Book.all
end
if you need anything else, just ask in comments and i will edit. Also sorry if im not explaining correctly.
CodePudding user response:
In your books#index
controller action
def index
@books = Book.all
@books = @books.where(user_id: params[:user_id]) if params[:user_id].present?
end
And in your users#show
view
link_to "This user books", books_path(user_id: @user.id)
So if you will go to /books
you will see all books
But if you click the link on user's page -- you will see only this user books
CodePudding user response:
For me, the best soluction is leave the default methods and create a new one:
def show_user_books
@books = Book.where(user_id:params[:user_id]).order(created_at: :desc) if params[:user_id].present?
redirect_to books_path
end