Reputation: 1402
I'm a Rails beginner and I'm currently adding some basic associations to my models. I have the following in my two models:
User model:
class User < ActiveRecord::Base
has_many :photos, dependent: :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_uniqueness_of :username
end
Photos model:
class Photo < ActiveRecord::Base
belongs_to :user
has_attached_file :image,
styles: { medium: '300x300>', thumb: '100x100>' },
default_url: '/images/:style/missing.png'
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
After adding the above, I ran the appropriate migrations:
rails g migration AddUserIdToPhotos user_id:integer
rake db:migrate
The user_id was added to the Photos table but when I add a new photo, the user_id field is set to nil. When I went to psql to double check there, it does not even show nil, just an empty field.
This is the code in the Photos Controller:
def create
photo = Photo.new(photo_params)
if photo.save
Pusher['the_force'].trigger('new_photo', {
url: photo.image.url(:medium),
description: photo.description,
id: photo.id
})
end
redirect_to '/'
end
private
def photo_params
params.require(:photo).permit(:image, :description, :user_id)
end
end
Any help here would be much appreciated.
Upvotes: 0
Views: 600
Reputation: 4870
If you are not passing the user from your form and you wants to save the user that is already logged in, you have to pass it when creating the photo instance.
photo = Photo.new(photo_params, :user => current_user)
Upvotes: 1