如何使用Ruby on Rails创建用户偏好的数据模型?
- 内容介绍
- 文章标签
- 相关推荐
本文共计319个文字,预计阅读时间需要2分钟。
我将利用StackOverflow作为我的案例库。假设我有一个问题模型。登录用户可以将问题标记为他们的最爱。在数据库中,这种事件可能存储在UserQuestions表中,其中包含user_id字段和q字段。
我将使用StackOverflow作为我的例子.假设我有一个问题模型.登录用户可以“标记”问题以标记为他们的最爱之一.在数据库中,这种事情可能会存储在UserQuestions表中,其中包含user_id字段和question_id字段.这种功能不是典型的CRUD,因为实际上只有“list”,“add”和“delete”. “用户加星标的问题”列表中显示的记录也应该不是UserQuestion记录,而是问题记录.我在控制器和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
本文共计319个文字,预计阅读时间需要2分钟。
我将利用StackOverflow作为我的案例库。假设我有一个问题模型。登录用户可以将问题标记为他们的最爱。在数据库中,这种事件可能存储在UserQuestions表中,其中包含user_id字段和q字段。
我将使用StackOverflow作为我的例子.假设我有一个问题模型.登录用户可以“标记”问题以标记为他们的最爱之一.在数据库中,这种事情可能会存储在UserQuestions表中,其中包含user_id字段和question_id字段.这种功能不是典型的CRUD,因为实际上只有“list”,“add”和“delete”. “用户加星标的问题”列表中显示的记录也应该不是UserQuestion记录,而是问题记录.我在控制器和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

