【问题标题】:How can I get all posts from a specific user如何获取特定用户的所有帖子
【发布时间】:2013-07-28 18:29:50
【问题描述】:

我正在 Rails 上创建我自己的博客,其中包含帖子和用户。当我点击他时,我需要显示来自特定作者的所有帖子(这里的概念:link)。我该怎么办? 请说我应该添加哪些额外的信息或代码

users_controller:

class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@posts = @user.posts
  end

end

posts_controller:

class PostsController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :index]

# GET /posts
# GET /posts.json



def index
 @posts = Post.all

  respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @posts }
  end
end

# GET /posts/1
# GET /posts/1.json
def show
@post = Post.find(params[:id])

respond_to do |format|
  format.html # show.html.erb
  format.json { render json: @post }
  end
end

# GET /posts/new
# GET /posts/new.json
def new
 @post = Post.new

  respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @post }
  end
end

# GET /posts/1/edit
def edit
  @post = Post.find(params[:id])
 end

 # POST /posts
# POST /posts.json
 def create
#@post = Post.new(params[:post])
@post = current_user.posts.build(params[:post])
respond_to do |format|
  if @post.save
    format.html { redirect_to @post, notice: 'Post was successfully created.' }
    format.json { render json: @post, status: :created, location: @post }
  else
    format.html { render action: "new" }
    format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
 end

# PUT /posts/1
# PUT /posts/1.json
def update
 @post = Post.find(params[:id])

 respond_to do |format|
  if @post.update_attributes(params[:post])
    format.html { redirect_to @post, notice: 'Post was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render action: "edit" }
    format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end

# DELETE /posts/1
# DELETE /posts/1.json
def destroy
@post = Post.find(params[:id])
@post.destroy

 respond_to do |format|
  format.html { redirect_to posts_url }
  format.json { head :no_content }
  end
 end
end

用户模型:

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
has_many :posts, :dependent => :destroy
validates :fullname,      :presence => true, :uniqueness => true
validates :password,      :presence => true
validates :email,         :presence => true, :uniqueness => true


devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

attr_accessible :email, :password, :password_confirmation, :fullname


end

后模型:

class Post < ActiveRecord::Base
attr_accessible :text, :title

validates :user_id, :presence => true
validates :title,   :presence => true
validates :text, :presence => true

belongs_to :user
has_many :comments
end

【问题讨论】:

标签: ruby-on-rails blogs


【解决方案1】:

这是对 Ruby on Rails 的相当直接的使用。我建议阅读Active Record Basics 以了解最新情况。

首先,您应该在 Posts 和 Users 之间建立一个如下所示的 belongs_to 关系:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

这会将.posts 方法添加到User 实例,并将.user 方法添加到Post 实例

然后您必须决定您希望应用程序的 URL 结构如何工作。以下是我脑海中的一些选择:

  1. /posts?user=:user_id
  2. /posts/by/:user_id
  3. /users/:id/posts

鉴于用户与其帖子之间的关系,我的建议(我相信一般的“Rails 方式”)将是 #3。所以,让我们将路由添加到config/routes.rb

创建 JUST 路由的捷径:

get 'users/:id/posts' => 'users#posts', :as => :user_posts

基于resources创建路由的漫漫长路:

resources :users do
  member do
    get :posts
  end
end

这两种方法都将提供一个名为 user_posts_path 的辅助方法和一个名为 user_posts_url 的辅助方法,可在您的视图中使用 link_to 辅助方法链接到用户帖子列表: p>

<%= link_to post.user.name, user_posts_path(post.user) %>

现在,您必须在app/controllers/users_controller.rb 中添加控制器操作:

class UsersController < ActionController::Base

  def posts
    @user = User.find(params[:id])
    @posts = @user.posts
  end

end

然后将您的 HTML/ERB 代码添加到 app/views/users/posts.html.erb

<% @posts.each do |post| %>
  <%= post.inspect %>
<% end %>

这应该使您具备显示用户帖子的基本能力。您可以通过重用部分帖子或其他一些不错的快捷方式来增强它,但我将把它作为练习留给您弄清楚。

【讨论】:

  • 我已经使用“get 'users/:id/posts' => 'users#posts', :as => :user_posts”设置了路线,但我仍然得到 No route matches [GET ] "/users/1/posts" 错误。知道可能出了什么问题吗?
【解决方案2】:

您需要 2 个模型:用户和帖子。它们之间有一个关系:用户有很多帖子,帖子属于用户。要在数据库中创建此关系,您应该将 user_id 列添加到 posts 表中。为此,只需运行以下命令:

rails generate migration AddUserIdToPosts user_id: integer

不要忘记在那之后运行 rake db:migrate

要创建模型之间的关联,请添加到用户模型:

has_many :posts, dependent: :destroy

并发布模型:

belongs_to :user

现在您可以在帖子上使用“用户”方法,在用户上使用“帖子”方法。例如在用户控制器的显示操作中:

@user = User.find(params[:id])
@posts = @user.posts

此链接将帮助您: http://guides.rubyonrails.org/association_basics.html http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

【讨论】:

  • 非常感谢您的回答,但在我按照您所说的操作后发生了错误:ActiveRecord::RecordNotFound in UsersController#show 找不到没有 ID 的用户
  • 显示用户控制器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 2017-01-12
  • 1970-01-01
  • 2022-06-29
相关资源
最近更新 更多