需要帮助创建GET路由



我需要帮助实现一个路由获取所有博客文章的author_ids。

  • 我们要获取的文章需要在传递的author_ids参数中指定至少一个作者。我创建了一个辅助函数来帮助我通过ID获取所有博客文章,Post.get_posts_by_user_id
  • 我还需要按给定的查询参数对帖子进行排序。另外,我需要尽可能有效地删除任何重复的帖子。

我在这里被难住了,因为author_ids是给定的。(我对Ruby非常陌生)

这是我们应该从路由返回的内容:"posts": [{"id": 1, "likes": 960, "popularity": 0.13, "reads": 50361, "tags": ["tech", "health"], text": "Some text here."}, ... ]

期望提供给该路由的查询参数

更新:

创建索引方法后,似乎只获取一个帖子,而不是获取与authorIds中传递的相关的所有帖子。

def index
posts = current_user
.posts
.where(id: params[:authorIds].split(','))
.order(sort_column => sort_direction)
if posts
render json: { post: posts }, status: :ok
else
render json: {error: posts.errors}, status: :unprocessable_entity
end
end

测试用例

更新2:

Post模型:

class Post < ApplicationRecord

# Associations
has_many :user_posts
has_many :users, through: :user_posts, dependent: :destroy
# Validations
validates :text, presence: true, length: { minimum: 3 }
validates :popularity, inclusion: { in: 0.0..1.0 }
def tags
if super
super.split(",")
end
end
def tags=(value)
if value.kind_of? Array
super value.join(",")
else
super value
end
end
def self.get_posts_by_user_id(user_id)
Post.joins(:user_posts).where(user_posts: { user_id: user_id })
end
end
用户模式:

class User < ApplicationRecord
has_secure_password
# Associations
has_many :user_posts
has_many :posts, through: :user_posts, dependent: :destroy
# Validations
validates :username, :password, presence: true
validates :password, length: { minimum: 6 }
validates :username, uniqueness: true
end

User_post模型:

class UserPost < ApplicationRecord
belongs_to :user
belongs_to :post
end

我想这样做。

def index
author_ids_array = params[:ids].to_s.split(',')
Post
.get_posts_by_user_id(author_ids_array)
.order(sort_column => sort_direction)
end
private
def sort_column
allow_list = %w[id reads likes popularity]
params[:sortBy].presence_in(allow_list) || allow_list.first
end
def sort_direction
allow_list = %w[asc desc]
params[:direction].presence_in(allow_list) || allow_list.first
end

最新更新