使用devise current_user

时间:2014-06-18 13:55:47

标签: ruby ruby-on-rails-4 devise associations

我有一个用户和一个地址,例如,关系如下:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_one :address
end


class Address< ActiveRecord::Base
  belongs_to :user
end

现在,当我创建一个地址对象时,我希望能够通过current_user id并将其保存到地址模型,所以在我的控制器中我有

before_filter :authenticate_user!

def new
  @address= current_user.address.new
end

def create
  @address= current_user.address.new(address_params)
   if @address.save
     redirect_to root_path, notice: 'Address Successfully Created'
  else
    render action: 'new'
  end
end

private

def address_params
  params.require(:address).permit(:id, :user_id, :add_1, :add_2, :add_3)
end

我目前无法访问新动作,因为我得到的错误是

undefined method `new' for nil:NilClass

我错过了什么?

1 个答案:

答案 0 :(得分:3)

我认为你应该这样做:

def new
  @address = current_user.build_address
end

同样在create行动

更多信息here