3

I'll use StackOverflow as my example. Let's say I have a Question model. A logged in user can "star" a Question to mark is as one of their favorites. In the database, this sort of thing would probably be stored in a UserQuestions table with a user_id field and a question_id field. This sort of feature is not typical CRUD since there is really only "list", "add", and "delete". Also the records being displayed on the "User starred questions" list should be not UserQuestion records but instead Question records. What code do I put in my controller and UserQuestion model?

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
Coder
  • 1,917
  • 3
  • 17
  • 33
Andrew
  • 227,796
  • 193
  • 515
  • 708

1 Answers1

7

I'd say this is typical crud if you stick with convention. Add is create, remove is destroy.

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
mark
  • 10,316
  • 6
  • 37
  • 58
  • I haven't seen this syntax before in any tutorials that I've read: `@user.favourites << @question`. Does this save the User model? Or do I still need to do that? – Andrew Aug 19 '11 at 04:08
  • Also, how would you link to the "create" action? Eventually, I plan on doing an AJAX request to POST to the "create" action, but what can I do so that this works without javascript? – Andrew Aug 19 '11 at 04:44
  • The assignment does save the association. See http://guides.rubyonrails.org/association_basics.html#has_many-association-reference The create action I'd have as a button_to with remote => true and using rails 3 javscript helpers. See http://asciicasts.com/episodes/205-unobtrusive-javascript – mark Aug 19 '11 at 10:17
  • I keep getting a "stack level too deep" error and can't figure out why that is. I think it has something to do with the model associations. – Andrew Aug 23 '11 at 04:50
  • Ah nevermind, figured it out. I had duplicate `:has_many :user_favorites` – Andrew Aug 23 '11 at 05:05