2011-06-18 31 views
0

我跟隨了這些問題(onetwo)關於如何僅用當前用戶調整我的方法,以便他們具有特定的user_id來編輯,更新,創建和銷燬其產品。@ mymodel.user = current_user對我不起作用

這裏是我的代碼:

我的遷移:

class CreateProducts < ActiveRecord::Migration 
    def self.up 
    create_table :products do |t| 
     t.string :name 
     t.date :date 
     t.decimal :price, :default => 0, :precision => 10, :scale => 2 
     t.integer :user_id 
     t.float :latitude 
     t.float :longitude 

控制器:

class ProductsController < ApplicationController 
    before_filter :authenticate_user! 

    def index 
    @products = Product.all 

    def show 
    @product = Product.find(params[:id]) 

    def new 
    @product = Product.new 

    def edit 
    @product.user = current_user 
    @product = Product.find(params[:id]) 
    end 

    def create 
    @product.user = current_user 
    @product = Product.new(params[:product]) 

    def update 
    @product.user = current_user 
    @product = Product.find(params[:id]) 


    def destroy 
    @product.user = current_user 
    @product = Product.find(params[:id]) 
    @product.destroy 

產品型號:

class Product < ActiveRecord::Base 
    attr_accessible :name, :date, :price, :tag_list 
    belongs_to :user 
end 

則設計用戶模型:

class User < ActiveRecord::Base 

    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
    attr_accessible :email, :password, :password_confirmation, :remember_me 

    has_many :products,  :dependent => :destroy 

我嘗試提交它,然後突然一個彈出:

NoMethodError中的ProductsController#創建

undefined method `user=' for nil:NilClass 

我缺少什麼或者做錯了什麼?

在此先感謝!

回答

2

您正在嘗試在產品之前分配@ product.user。先查找產品,然後分配用戶。

@product = Product.find(params[:id]) 
@product.user = current_user 

對於要限制該產品的CURRENT_USER比創建其他的行動,你可以做這樣的事情(假設你安裝了has_many :products商會在User模型。

@product = current_user.products.find(params[:id]) 

那將制約發現只是那些有USER_ID等於CURRENT_USER產品。

+0

哇哦不知道爲了要緊!我以爲所有的行動得到在同一時間產生的。這工作,我可以創建它,但我可以仍然如其他用戶,銷燬和編輯其他用戶產品。我如何糾正這一點? – LearningRoR

+0

見補充我的回答。 –

+0

非常感謝主席先生! – LearningRoR