0
votes

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.

1
How do you add a new photo? Are you passing the user?Rafa Paez
Hi Rafa. I choose a field, fill out the description and then upload it. You can only post a photo once you are signed in so I was under the assumption that it's implied?Maikon
You have to assign the current_user to the photo before save it. Show me the controllers' code.Rafa Paez
class UsersController < ApplicationController def new @ user = User.new end def show @user = User.find_by(:username => params[:id]) end endMaikon
the code of the controller that add the photo to the database.Rafa Paez

1 Answers

1
votes

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)