Reputation: 11
I have two controllers- a ProfilesController and a UsersController. I have a page full of blog posts, and I want each to have a link to the profile of the user who created them. I've been having a wee problem with this lately, and I want to start fresh, but don't know where to begin. How can I go about this?
Post controller:
def index
if params[:search]
@posts = Post.search(params[:search]).order("created_at DESC").paginate(page: params[:page], per_page: 5)
else
@posts = Post.all.order('created_at DESC').paginate(page: params[:page], per_page: 5)
end
end
Profiles model:
class Profile < ApplicationRecord
belongs_to :user
end
Users model:
class User < ApplicationRecord
has_secure_password
validates :username, uniqueness: true
has_many :posts, foreign_key: :author
has_many :comments, foreign_key: :author
has_one :profile, foreign_key: :user
after_create :build_profile
def build_profile
Profile.create(user: self) # Associations must be defined correctly for this syntax, avoids using ID's directly.
end
end
BTW not using Devise
Upvotes: 1
Views: 157
Reputation: 809
How are your SQL tables? It would be best if your Posts table have a user_id field, that way you could search the user by id (user_id) and process the link via:
<%= link_to 'Post Owner', user_path(post.user_id) %>
Check to see if it works for you and let me know.
Upvotes: 1
Reputation: 668
Firstly, We get object profile
of each posts like this (you should try it in rails console):
@posts.first.user.profile # get the profile of first post
After that, we use profile_path
to generate link to profiles#show
(Of course, you need to define a controller Profile
)
profile_path(@posts.first.user.profile)
I often do it in view
, not in controller
.
Happy coding!
Upvotes: 0