[英]How can I generate a link to the ID of a profile?
我有兩個控制器——一個 ProfilesController 和一個 UsersController。 我有一個充滿博客文章的頁面,我希望每個頁面都有一個指向創建它們的用戶的個人資料的鏈接。 我最近遇到了一個小問題,我想重新開始,但不知道從哪里開始。 我該怎么辦?
后控制器:
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_path
鏈接(當然,您需要定義一個控制器Profile
)
profile_path(@posts.first.user.profile)
我經常在view
這樣做,而不是在controller
。
快樂編碼!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.