0

I have Two models Users and Profiles ( Users is from devise ). A user can have many profiles , so i created a migration to add user_id to Profiles.

class Profile < ActiveRecord::Base
belongs_to :user

attr_accessible :description, :name, :product, :image, :price , :user_id
mount_uploader :image, ImageUploader
validates_presence_of :name, :product,:image, :price
end

class User < ActiveRecord::Base

# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me

# attr_accessible :title, :body
has_many :profiles
validates_associated :profiles
end

In my profiles controller , i have a new method to create a new profile. I want that when user logs in, he is able to see only his profiles not all. def new

@profile = current_user.profiles.build

#@profile = @user.profile.new

respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @profile }
end

end

Ideally, my user_id column should be updated with build, but my user_id does not get updated and that is why profiles are not displayed . i am using postgresql with pg gem and when i manually add the user_id for that profile , i am able to see the profiles.

Please help to solve this, i am able to figure this out since a long time.Let me know if you want more information to solve this.

Mindtrades
  • 11
  • 2

1 Answers1

0

Maybe try something like this in your controller:

if current_user.profiles.count == 0
  profile = Profile.create
  current_user.profiles << profile
end
Fa11enAngel
  • 4,690
  • 2
  • 39
  • 38
  • It gives me error for my view now, undefined method `model_name' for NilClass:Class 1: <%= form_for @profile, :html => { :class => 'form-horizontal' } do |f| %> 2:
    3: <%= controller.action_name.capitalize %> Profile . What change should i do in my view
    – Mindtrades Jan 15 '13 at 01:08