gpt4 book ai didi

ruby-on-rails - ruby rails : How to model a "user favorite model"

转载 作者:行者123 更新时间:2023-12-03 16:20:43 25 4
gpt4 key购买 nike

我将使用 StackOverflow 作为示例。假设我有一个 Question 模型。登录用户可以为问题“加注星标”,将其标记为他们的最爱之一。在数据库中,这种事情可能会存储在一个 UserQuestions 表中,该表具有一个 user_id 字段和一个 question_id 字段。这种功能不是典型的 CRUD,因为实际上只有“列表”、“添加”和“删除”。此外,显示在“用户已加星标的问题”列表中的记录不应是 UserQuestion 记录,而是 Question 记录。我应该在我的 Controller 和 UserQuestion 模型中放入什么代码?

class MyFavoriteQuestionsController < ApplicationController

def index
#list just the questions associated with current_user
end

def add
#insert a row in the database for current_user and selected question
def

def remove
#remove the row from the database
end
end

最佳答案

如果您坚持惯例,我会说这是典型的垃圾。添加即创建,删除即销毁。

class FavouritesController < ApplicationController

before_filter :find_user

def index
@favourites = @user.favourites
end

def create
@question = Question.find params[:id]
@user.favourites << @question
def

def destroy
@favourite = @user.favourites.find_by_question_id params[:id]
@favourite.destroy unless @favourite.blank?
end
end


#routes.rb

resources :users do
resources :favourites, :only => [:index, :create, :destroy]
end

#user.rb

has_many :user_favourites, :dependent => :destroy
has_many :favourites, :through => :user_favourites, :source => :question

关于ruby-on-rails - ruby rails : How to model a "user favorite model",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7021026/

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