如何链接到用户个人资料的ID?

时间:2019-01-25 04:03:22

标签: ruby-on-rails ruby

我有两个控制器-ProfilesControllerUsersController。我有一个充满博客文章的页面,我希望每个文章都有指向创建它们的用户的 profile 的链接。我最近一直对此感到毛骨悚然,我想重新开始,但不知道从哪里开始。我该怎么办?

后置控制器:

 def index
    @shit = Static.all.order('id DESC')
  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
  

顺便说一句不使用Devise

2 个答案:

答案 0 :(得分:0)

使用joins

def index
  @shit = Static.all.order('id DESC')
  scope = 
    if params[:search]
      Post.search(params[:search])
    else
      Post.all
    end

  @posts =
    scope.
      joins(:users).
      joins(:profiles).
      order("created_at DESC").
      paginate(page: params[:page], per_page: 5)
end

答案 1 :(得分:0)

在单个@post对象中,您应该与所有者(用户)相关。在您的视图中,为user_path使用每个路由,但为它提供@post.user

视图示例

<% @posts.each do |post| %> <%= link_to user_path(post.user) %> //Rest of post content <% end %>