gpt4 book ai didi

ruby-on-rails - Rails 用户 has_many posts, has_many favorite_posts

转载 作者:行者123 更新时间:2023-12-02 08:08:27 25 4
gpt4 key购买 nike

首先对英语感到抱歉

所以我已经有了“用户 - 帖子”一对多关联,这意味着每个帖子只能有一个作者,现在我想在用户个人资料中添加“最喜欢的帖子”按钮,以及“添加到收藏夹”按钮每个帖子,所以问题是如何实现这种正确的方式?我应该修改我的用户 - 发布关联吗?或创建其他模型?我,有点糊涂。提前致谢!

其实我想要这个结果:

@user.posts #返回该用户创建的所有帖子

@user.favorite_posts #返回该用户添加到收藏夹的帖子

这是我的用户模型:

class User < ApplicationRecord

mount_uploader :avatar, ImageUploader
validates :username, presence: true, uniqueness: true, length: {in: 3..20}

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

has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :ratings
enum role: [ :user, :admin ]

def calculate_average
ratings.blank? ? 0 : ratings.map(&:value).inject(:+) / ratings.count.to_f
end
end

帖子模型:

class Post < ApplicationRecord
mount_uploader :image, ImageUploader
validates :body, presence: true
validates :title, presence: true, length: { maximum: 50}

belongs_to :user
has_many :comments, dependent: :destroy
end

编辑

好吧,看看我是怎么做到的,它完全按照我想要的方式工作。

这是我的用户模型:

class User < ApplicationRecord

mount_uploader :avatar, ImageUploader
validates :username, presence: true, uniqueness: true, length: {in: 3..20}

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

has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :ratings
has_many :favorites, dependent: :destroy
has_many :favorite_posts, through: :favorites, source: "post"
enum role: [ :user, :admin ]

def calculate_average
ratings.blank? ? 0 : ratings.map(&:value).inject(:+) / ratings.count.to_f
end
end

最佳答案

你需要many-to-many最喜欢的帖子的关系,首先运行这个命令来创建一个表 favorite_posts

rails g model FavoritePost user:references post:references

然后

rails db:migrate

然后将这些添加到您的模型中,如下所示:

#=> model/user.rb
class User < ApplicationRecord
has_many :favorite_posts, dependent: :destroy # or you can use only this line except second if you will face any problem
has_many :posts, through: :favorite_posts
end

#=> model/post.rb
class Post < ApplicationRecord
has_many :favorite_posts, dependent: :destroy
has_many :users, through: :favorite_posts
end

#=> model/favorite_post.rb
class FavoritePost < ApplicationRecord
belongs_to :user
belongs_to :post
end

那是关系部分,现在创建一个最喜欢的帖子部分。对于新代码,您可以创建一个 Controller ,即

rails g controller favorites

然后是你的路由文件:

resources :favorites

使用 rake routes 的新路由示例:

    favorites GET    /favorites(.:format)          favorites#index
POST /favorites(.:format) favorites#create
new_favorite GET /favorites/new(.:format) favorites#new
edit_favorite GET /favorites/:id/edit(.:format) favorites#edit
favorite GET /favorites/:id(.:format) favorites#show
PATCH /favorites/:id(.:format) favorites#update
PUT /favorites/:id(.:format) favorites#update
DELETE /favorites/:id(.:format) favorites#destroy

在你的 View 文件中添加如下内容:

# For creating favorite
<%= link_to "Favorite", favorites_path(user: current_user, post: post.id), class: 'btn bf-save-btn', method: :post, data: {disable_with: "Saving..."}, title: "Add to favorite" %>

# For deleting favorite list
<%= link_to "Unfavorite", favorite_path(post.id), class: 'btn af-save-btn', method: :delete, data: {disable_with: "Removing...."}, title: "Remove from favorite" %>

favorites_controller.rb 中:

def index
@saves = current_user.favorite_post
end
# index.html.erb
<% @saves.each do |fav| %>
<%= link_to fav.post.post_title, post_path(fav.post) %>
<% end %>

def create
@save = FavoritePost.new(post_id: params[:post], user: current_user)

respond_to do |format|
if @save.save
flash[:success] = 'Saved'
format.html { redirect_to request.referer }
format.xml { render :xml => @save, :status => :created, :location => @save }
else
format.html { redirect_to request.referer }
format.xml { render :xml => @save.errors, :status => :unprocessable_entity }
end
end
end

def destroy
post = Post.find(params[:id])
@save = FavoritePost.where(user_id: current_user.id, post_id: post.id).first

respond_to do |format|
if @save.destroy
flash[:error] = 'Unsaved'
format.html { redirect_to request.referer, status: 303 }
format.js { redirect_to request.referer, status: 303 }
# format.xml { head :ok }
end
end
end

这就是最喜欢/最不喜欢的功能。现在您需要为何时显示 Favorite 以及何时显示 Unfavorite 创建一些逻辑。

因为这个要求有很多种方式,首先你需要了解这个然后你可以随心所欲。

此外,要在不重新加载页面的情况下实现此目的,您可以尝试一些 Ajax

更新

class User < ApplicationRecord

mount_uploader :avatar, ImageUploader
validates :username, presence: true, uniqueness: true, length: {in: 3..20}

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

has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :ratings

# Newly added
has_many :favorite_posts, dependent: :destroy # or you can use only this line except second if you will face any problem
has_many :posts, through: :favorite_posts

enum role: [ :user, :admin ]

def calculate_average
ratings.blank? ? 0 : ratings.map(&:value).inject(:+) / ratings.count.to_f
end
end

希望对您有所帮助。

关于ruby-on-rails - Rails 用户 has_many posts, has_many favorite_posts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49299411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com