Reputation: 15374
I have a user and an address for example and the relation is as follows:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :address
end
class Address< ActiveRecord::Base
belongs_to :user
end
Now when I create an address object, I want to be able to pass through the current_user id and save it to the address model, so in my controller I have
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
I can't access the new action at the moment, as the error I am getting is
undefined method `new' for nil:NilClass
What am I missing?
Upvotes: 1
Views: 57
Reputation: 10825
I think you should do it like this:
def new
@address = current_user.build_address
end
And same in create
action
More info here
Upvotes: 3