开发者

Add user_id in photo uploaded

开发者 https://www.devze.com 2023-02-22 20:28 出处:网络
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.

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:

  1. add user_id in photos table

  2. add belongs_to :userin Photo model

  3. add has_many :photos in your User model

  4. add a hidden field in you photo form f.hidden_field :user_id, current_user

  5. beware to set user_id as attr_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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号