Commit c669b10

mo khan <mo@mokhan.ca>
2013-06-13 13:11:19
create association between user and cake
1 parent 0915e74
app/controllers/cakes_controller.rb
@@ -15,12 +15,12 @@ class CakesController < ApplicationController
   end
 
   def edit
-    @cake = Cake.find(params[:id])
+    @cake = current_user.cakes.find(params[:id])
     @categories = Category.all
   end
 
   def create
-    @cake = Cake.new(params[:cake])
+    @cake = current_user.cakes.create(params[:cake])
     if @cake.save
       redirect_to @cake, notice: 'Cake was successfully created.'
     else
@@ -29,7 +29,7 @@ class CakesController < ApplicationController
   end
 
   def update
-    @cake = Cake.find(params[:id])
+    @cake = current_user.cakes.find(params[:id])
     if @cake.update_attributes(params[:cake])
       redirect_to @cake, notice: 'Cake was successfully updated.'
     else
@@ -38,7 +38,7 @@ class CakesController < ApplicationController
   end
 
   def destroy
-    @cake = Cake.find(params[:id])
+    @cake = current_user.cakes.find(params[:id])
     @cake.destroy
     redirect_to cakes_url
   end
app/models/cake.rb
@@ -1,6 +1,7 @@
 class Cake < ActiveRecord::Base
   attr_accessible :name, :photo, :photo_cache, :category_id
   belongs_to :category
+  belongs_to :user
   mount_uploader :photo, PhotoUploader
 
   def slug
app/models/user.rb
@@ -2,4 +2,5 @@ class User < ActiveRecord::Base
   devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :token_authenticatable
 
   attr_accessible :email, :password, :password_confirmation, :remember_me
+  has_many :cakes
 end
db/migrate/20130613130944_add_user_id_to_cakes.rb
@@ -0,0 +1,5 @@
+class AddUserIdToCakes < ActiveRecord::Migration
+  def change
+    add_column :cakes, :user_id, :integer
+  end
+end
db/schema.rb
@@ -11,7 +11,7 @@
 #
 # It's strongly recommended to check this file into your version control system.
 
-ActiveRecord::Schema.define(:version => 20130613130424) do
+ActiveRecord::Schema.define(:version => 20130613130944) do
 
   create_table "cakes", :force => true do |t|
     t.string   "name"
@@ -19,6 +19,7 @@ ActiveRecord::Schema.define(:version => 20130613130424) do
     t.datetime "updated_at",  :null => false
     t.string   "photo"
     t.integer  "category_id"
+    t.integer  "user_id"
   end
 
   create_table "categories", :force => true do |t|