Add user_id in photo uploaded
Using RoR 2.3.8.
I let users to upload photos using paperclip, but there is no o开发者_JS百科wnership in the photo. Which means, I don't know who uploaded the photos at all.
Here, I would like to have a new column in Photos model, user_id
and everytime a user uploads a picture, his ID will be automatically included in the column.
How do I do that? Thanks!
There are two three ways of doing this.
Either add the new photo to the user's photo collection:
current_user.photos << Photo.new(params[:photo])
Or like this:
current_user.photos.build(params[:photo])
Or assign the logged in (current) user to the new photo:
photo = Photo.new(params[:photo])
photo.user = current_user
I'd say:
add
user_id
in photos tableadd
belongs_to :user
in Photo modeladd
has_many :photos
in your User modeladd a hidden field in you photo form
f.hidden_field :user_id, current_user
beware to set
user_id
asattr_accessible
If ever you fear user hack the html and add photos for other, you should merge params in your controller instead of adding a field in the form.
class User < ActiveRecord::Base
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :user
end
In your migration file, set a column with an integral value called "user_id" in the photo model
Then you can call
@user.photos
or
@photo.user
If you are using Devise gem - just add this to your photo_controller:
def create
@photo.user = current_user
...
end
精彩评论