如何生成指向配置文件ID的链接



我有两个控制器-一个ProfilesController和一个UsersCoontroller。我有一个充满博客文章的页面,我希望每个博客文章都有一个链接,指向创建这些文章的用户的个人资料。我最近遇到了一个小问题,我想重新开始,但不知道从哪里开始。我该怎么办?

后控制器:

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

配置文件型号:

class Profile < ApplicationRecord
belongs_to :user
end

用户型号:

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

您的SQL表怎么样?最好是Posts表有一个user_id字段,这样你就可以通过id(user_id)搜索用户,并通过处理链接

<%= link_to 'Post Owner', user_path(post.user_id) %>

检查一下它是否适合你,然后告诉我。

首先,我们得到每个帖子的对象profile,如下所示(您应该在rails控制台中尝试):

@posts.first.user.profile # get the profile of first post

之后,我们使用profile_path生成到profiles#show的链接(当然,您需要定义一个控制器Profile)

profile_path(@posts.first.user.profile)

我经常在view中这样做,而不是在controller中。

编码快乐!

最新更新