开发者

@mymodel.user = current_user is not working for me

I followed these questions(one and two) on how to adjust my methods with the current user only so they have the specific user_id to edit,update, create and destroy their products.

Here is my code:

My Migration:

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

the Controller:

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])
开发者_StackOverflow社区  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

Product Model:

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

then the Devise User Model:

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

I try to submit it and then suddenly this pops up:

NoMethodError in ProductsController#create

undefined method `user=' for nil:NilClass

What am i missing or doing wrong?

Thanks in advance!


You are trying to assign @product.user before you have a product. Do your find on the product first, then assign the user.

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

For the actions other than create where you want to restrict the product to the current_user, you can do something like this (assuming you setup the has_many :products association in your User model.

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

That will restrict find to just those products that have the user_id equal to the current_user.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜