2011-06-18 15 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 

私はそれを提出しようとすると、突然これがポップアップ表示されます:ProductsController#で

NoMethodErrorを私は何をしないか、間違ってやっている

undefined method `user=' for nil:NilClass 

を作成しますか?

ありがとうございます!

答えて

2

製品を取得する前に、@ product.userを割り当てようとしています。最初に製品を見つけてから、ユーザーを割り当てます。あなたはCURRENT_USERに製品を制限したい場所を作成し、あなたがこのような何か(あなたのUserモデルで、あなたのセットアップを想定しhas_many :products関連付けを行うことができるよりも、他のアクションのために

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

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

ことuser_idがcurrent_userと等しい製品に限定して検索します。

+0

オーダーは重要なことを知らなかった!私はすべてのアクションが同時に発生すると思った。まだ他のユーザーは、他のユーザーの製品を破壊し、編集します。どのように私はこれを修正するのですか? – LearningRoR

+0

私の答えの追加を見てください。 –

+0

ありがとうございました! – LearningRoR

関連する問題