【问题标题】:Devise - how to show user's post设计 - 如何显示用户的帖子
【发布时间】:2014-09-14 08:47:05
【问题描述】:
我使用 Devise gem 进行身份验证。
在数据库中,我的数据库架构(和 Post 控制器)中有用户表和帖子表。
在帖子控制器中,我想找到分配给特定用户的所有帖子。我在帖子表中有 user_id。
如何获取所有用户的帖子或如何检查是否为已登录用户分配了特定帖子。
我想过这样的事情(当然只是伪代码:
current_user.id == Post.where(params:[post_id]).user_id
那么如何在 Devise 中获取当前用户 id 以及如何检查当前用户 id 与 eg 相同。分配给查看帖子的 user_id(我想在当前用户为帖子所有者时添加“编辑”功能)以及如何查找当前用户为所有者的所有帖子。
【问题讨论】:
标签:
ruby-on-rails
ruby
activerecord
devise
【解决方案1】:
协会
首先,posts 表中的user_id 列就是所谓的foreign_key
外键用于关系数据库系统,使您能够从单个记录中调用关联数据。简而言之,这意味着您将能够使用ActiveRecord associations 来调用您需要的数据,而不必单独调用它:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :posts
end
#app/models/post.rb
class Post < ActiveRecord::Base
belongs_to :user
end
这将使您能够使用以下调用:
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
@posts = current_user.posts
end
end
您最好查找has_many association:
修复
关于向用户显示您的帖子,您需要确保设置了正确的“流程”。我的意思是您需要一些条件才能知道您的用户是否已登录以及是否设置了 @posts:
#app/views/posts/index.html.erb
<% if @posts.present? %>
<% @posts.each do |post| %>
<%= post.title %>
<% end %>
<% end %>
【解决方案2】:
也许这是您第一次使用 Devise。您可以在控制器或视图中访问current_user。我想你可以做这样的事情
在控制器中 (posts_controller.rb):
@posts = current_user.posts
在视图中(posts/show.html.erb,我猜):
if current_user.id = @post.current_user
#render something here
end
【解决方案3】:
获取当前用户为所有者的所有帖子。
@posts = Post.where(:user_id => current_user.id)
在你看来
<%-# commented : checking if @posts is empty -%>
<% if @posts.empty? %>
<span>Sorry, post is empty </span>
<% else %>
<%= @posts.each do |p| %>
<% if p.user_id == current_user.id %>
<% link_to "edit", edit_path(p) %>
<% end %>
<% end %>
<% end %>
【解决方案4】:
您可以通过多种方式获取 current_user 帖子。我会走很远的路。
我们需要
- 一个动作
- 一个动作视图和一个部分
- 一条路线
- 链接到
* 动作 *
def my_posts
@posts = current_user.posts.all.order(created_at: 'DESC')
end
* 查看 *
my_posts.html.erb
<% if @posts.present? %>
<%= render 'posts' posts: @posts %>
<% else %>
<h1>You don't have any posts yet! create one</h1>
<% end %>
_posts.html.erb
<%posts.each do |post| %>
<%= post.title %>
<% end %>
index.html.erb
<%= render 'posts' posts: @posts %>
路线
get 'post' => 'posts#my_posts', as: :my_posts
link_to
<%= link_to 'My posts', my_posts_path %>
我可能会迟到,但有人会发现它很有用:)