@ mymodel.user = current_user对我不起作用

时间:2011-06-18 16:30:35

标签: ruby-on-rails devise

我按照这些问题(onetwo)了解了如何仅使用当前用户调整我的方法,以便他们拥有特定的user_id来编辑,更新,创建和销毁他们的产品。

这是我的代码:

我的移民:

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 #create

undefined method `user=' for nil:NilClass

我错过了什么或做错了什么?

提前致谢!

1 个答案:

答案 0 :(得分: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的产品。

相关问题