3

例として StackOverflow を使用します。Question私がモデルを持っているとしましょう。Questionログインしたユーザーは、お気に入りの 1 つとして「スター」を付けることができます。データベースでは、この種のものはおそらくフィールドとフィールドを持つUserQuestionsテーブルに格納されます。実際には「リスト」、「追加」、「削除」しかないため、この種の機能は典型的な CRUD ではありません。また、「ユーザーのスター付き質問」リストに表示されるレコードは、レコードではなく、レコードである必要があります。コントローラーとモデルに入れるコードは何ですか?user_idquestion_idUserQuestionQuestionUserQuestion

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
4

1 に答える 1

7

慣例に固執するなら、これは典型的なクラッドだと思います。追加は作成、削除は破棄です。

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
于 2011-08-11T07:00:58.113 に答える