I am using CarrierWave as my photo albums, and I am trying to setup so I can prevent users from only being able to upload maximum 5 photos to their gallery. However I am getting back a "undefined method `user'" error when clicking on the Upload Photo button with page title "NoMethodError in PhotosController#create"
Photo.rb:
class Photo < ActiveRecord::Base
attr_accessible :title, :body, :gallery_id, :name, :image, :remote_image_url
belongs_to :gallery
mount_uploader :image, ImageUploader
LIMIT = 5
validate do |record|
record.validate_photo_quota
end
def validate_photo_quota
return unless self.user
if self.user.photos(:reload).count >= LIMIT
errors.add(:base, :exceeded_quota)
end
end
end
Photos_controller:
class PhotosController < ApplicationController
def new
#photo = Photo.new(:gallery_id => params[:gallery_id])
end
def create
#photo = Photo.new(params[:photo])
if #photo.save
flash[:notice] = "Successfully created photos."
redirect_to #photo.gallery
else
render :action => 'new'
end
end
def edit
#photo = Photo.find(params[:id])
end
def update
#photo = Photo.find(params[:id])
if #photo.update_attributes(paramas[:photo])
flash[:notice] = "Successfully updated photo."
redirect_to #photo.gallery
else
render :action => 'edit'
end
end
def destroy
#photo = Photo.find(params[:id])
#photo.destroy
flash[:notice] = "Successfully destroyed photo."
redirect_to #photo.gallery
end
end
I thought I previously had user defined unless it has to be done for every controller?
You're calling self.user into the Photo model. The keyword self in that case represent an instance of photo. By your definition, a photo belongs to a gallery and therefore, there is no user to be called from photo.
If a gallery belongs to a user, then you should be able to call self.gallery.user to select the user owner of that photo.
You can also define a has_many :through association so as you can directly call the user from that photo, or retrive all the photos from that user.
This can be done following the documentation. In your case:
class User < ActiveRecord::Base
has_many :galeries
has_many :photos, :through => :galeries
end
class Photo < ActiveRecord::Base
belongs_to :user, :through => :gallery
belongs_to :gallery
end
class Gallery < ActiveRecord::Base
belongs_to :user
has_many :photos
end
Then you should be able to call photo.user and get the owner of the picture.
Related
I have the following code letting a user to create a new album through a join table with an extra params (creator).
In order to do it, my controller does 2 requests (one for creating the album object and the collaboration object / the other to update the collaboration object with the extra params).
I would like to know if there is a way to do this call with only one request. (add the extra "creator" params in the same time than the album creation)
Thank you.
albums_controller.rb
class AlbumsController < ApplicationController
def new
#album = current_user.albums.build
end
def create
#album = current_user.albums.build(album_params)
if current_user.save
#album.collaborations.first.update_attribute :creator, true
redirect_to user_albums_path(current_user), notice: "Saved."
else
render :new
end
end
private
def album_params
params.require(:album).permit(:name)
end
end
Album.rb
class Album < ApplicationRecord
# Relations
has_many :collaborations
has_many :users, through: :collaborations
end
Collaboration.rb
class Collaboration < ApplicationRecord
belongs_to :album
belongs_to :user
end
User.rb
class User < ApplicationRecord
has_many :collaborations
has_many :albums, through: :collaborations
end
views/albums/new
= simple_form_for [:user, #album] do |f|
= f.input :name
= f.button :submit
You can just add associated objects on the new album instance:
#album = current_user.albums.new(album_params)
#album.collaborations.new(user: current_user, creator: true)
When you call #album.save ActiveRecord will automatically save the associated records in the same transaction.
class AlbumsController < ApplicationController
def new
#album = current_user.albums.new
end
def create
#album = current_user.albums.new(album_params)
#album.collaborations.new(user: current_user, creator: true)
if #album.save
redirect_to user_albums_path(current_user), notice: "Saved."
else
render :new
end
end
private
def album_params
params.require(:album).permit(:name)
end
end
You are also calling current_user.save and not #album.save. The former does work due to fact that it causes AR to save the associations but is not optimal since it triggers an unessicary update of the user model.
I'm trying to create a form with a series of checks to prevent duplicates during the simultaneous creation of three model records: one for the parent (assuming it doesn't exist), one for its child (assuming it doesn't exist), and one for a join table between the child and the User (to allow the User to have their own copy of the Song object).
In the current state of the code, The checks seemingly pass, but
the server logs show ROLLBACK, and nothing gets saved
to the database EXCEPT the parent object (artist).
When I try to use the ids of the object, I get the error undefined method id for nil:NilClass, or "couldn't find object without an ID".
The following code is in my controller:
class SongsController < ApplicationController
before_action :authenticate_user!
def create
#artist = Artist.find_by(name: params[:artist][:name].strip.titleize) #look for the artist
#song = Song.find_by(title: params[:artist][:songs_attributes]["0"][:title].strip.titleize)
if #artist.present? && #song.present?
#user_song = current_user.user_songs.find(#song_id)
if #user_song.present?
render html: "THIS SONG IS ALREADY IN YOUR PLAYLIST"
render action: :new
else
#user_song = UserSong.create(user_id: current_user.id, song_id: #song.id)
redirect_to root_path
end
elsif #artist.present? && !#song.present?
#song = #artist.songs.build(title: params[:artist][:songs_attributes]["0"][:title].strip.titleize, lyrics: params[:artist][:songs_attributes]["0"][:lyrics].strip)
#user_song = UserSong.create(user_id: current_user.id, song_id: #song.id)
redirect_to root_path
elsif !#artist.present?
#artist = Artist.create(name: params[:artist][:name].strip.titleize)
#song = #artist.songs.build(title: params[:artist][:songs_attributes]["0"][:title].strip.titleize, lyrics: params[:artist][:songs_attributes]["0"][:lyrics].strip)
#user_song = UserSong.create(user_id: current_user.id, song_id: #song.id)
redirect_to root_path
else
render html: "SOMETHING WENT WRONG. CONTACT ME TO LET ME KNOW IF YOU SEE THIS MESSAGE"
end
end
def index
#songs = Song.all
end
def new
#artist = Artist.new
#artist.songs.build
#user_song = UserSong.new(user_id: current_user.id, song_id: #song_id)
end
def show
#song_id = params["song_id"]
#song = Song.find(params[:id])
end
def destroy
UserSong.where(:song_id => params[:id]).first.destroy
flash[:success] = "The song has been from your playlist"
redirect_to root_path
end
def edit
#song = Song.find(params[:id])
#artist = Artist.find(#song.artist_id)
end
def update
end
private
def set_artist
#artist = Artist.find(params[:id])
end
def artist_params
params.require(:artist).permit(:name, songs_attributes: [:id, :title, :lyrics])
end
def set_song
#song = Song.find(params["song_id"])
end
end
The models:
class Artist < ApplicationRecord
has_many :songs
accepts_nested_attributes_for :songs, reject_if: proc { |attributes| attributes['lyrics'].blank? }
end
class Song < ApplicationRecord
belongs_to :artist
has_many :user_songs
has_many :users, :through => :user_songs
end
class UserSong < ApplicationRecord
belongs_to :song
belongs_to :user
end
Sorry if I haven't abstracted enough. Not really sure how, given that there's no error message, just a rollback (without any validations present in any of the controllers).
Thanks to #coreyward and his pointing out of the fat-model skinny-controller lemma (never knew that was a thing), I was able to cut the code down and arrive at a solution immediately. In my models, I used validates_uniqueness_of and scope in order to prevent duplication of records. In my controller, I used find_or_create_by to seal the deal.
To whom it may concern, the final code is as follows:
class SongsController < ApplicationController
before_action :authenticate_user!
def create
#artist = Artist.find_or_create_by(name: params[:artist][:name].strip.titleize)
#song = #artist.songs.find_or_create_by(title: params[:artist][:songs_attributes]["0"][:title].strip.titleize) do |song|
song.lyrics = params[:artist][:songs_attributes]["0"][:lyrics].strip
end
#user_song = current_user.user_songs.find_or_create_by(song_id: #song.id) do |user_id|
user_id.user_id = current_user.id
end
redirect_to root_path
end
class Song < ApplicationRecord
validates_uniqueness_of :title, scope: :artist_id
belongs_to :artist
has_many :user_songs
has_many :users, :through => :user_songs
end
class Artist < ApplicationRecord
validates_uniqueness_of :name
has_many :songs
accepts_nested_attributes_for :songs, reject_if: proc { |attributes| attributes['lyrics'].blank? }
end
class UserSong < ApplicationRecord
validates_uniqueness_of :song_id, scope: :user_id
belongs_to :song
belongs_to :user
end
I'm attempting to set limits on the amount of commenting users can do on particular post during the day. I have implemented the following (successfully) in my Post model to limit the amount of Posts they can create.
class Post < ActiveRecord::Base
validate :daily_limit, :on => :create
def daily_limit
# Small limit for users who just sign up
if author.created_at >= 14.days.ago
if author.created_posts.today.count >= 4
errors.add(:base, "Exceeds Your Daily Trial Period Limit(4)")
end
else
if author.created_posts.today.count >= author.post_limit_day
errors.add(:base, "Exceeds Your Daily Limit")
end
end
end
end
But, when I attempt to add similar restrictions to my Comment model
class PostComment < ActiveRecord::Base
validate :daily_limit, :on => :create
belongs_to :post, :counter_cache => true
belongs_to :user
def daily_limit
# Small limit for users who just sign up
if user.posted_comments.today.count >= 2
errors.add(:base, "Exceeds Your Daily Trial Period Limit(4)")
end
end
end
I am greeted with a undefined method 'posted_comments' for nil:NilClass error. I don't believe my user_id is being passed into my model correctly in order to access it with something like user.posted_comments.today.count>=2
My create action in my post_comments controller is as follows:
class PostCommentsController < ApplicationController
def create
#post = Post.find(params[:post_id])
#post_comment = #post.post_comments.create(post_comment_params)
#post_comment.user = current_user
if #post_comment.save
redirect_to #post
else
flash[:alert] = "Comment Not Added"
redirect_to #post
end
end
end
and the my hacked down User model is as follows:
class User < ActiveRecord::Base
has_many :created_posts, class_name: 'Post', :foreign_key => "author_id",
dependent: :destroy
has_many :posted_comments, class_name: 'PostComment', :foreign_key =>"user_id", dependent: :destroy
end
Thanks.
You are assigning the user after "create" in your controller
#post_comment = #post.post_comments.create(post_comment_params)
#post_comment.user = current_user
Try this:
#post_comment = #post.post_comments.build(post_comment_params)
#post_comment.user = current_user
I have tried to do this but was unsuccessful. There's also no postings covering this which is odd considering selecting Default photo is a option for every social network. I have the CarrierWave gem and I want to set it up so that the user can select their ProfileImage (default image) from photos they have already uploaded. This photo would be used site wide. It's like having an avatar, however the articles out there only show how to upload a avatar as oppose to selecting a avatar from your uploaded photos. I am sure this will be helpful to other people since this is a common feature.
Photos controller:
def new
#photo = Photo.new
end
def create
#photo = Photo.new(params[:photo])
#photo.user = current_user
if #photo.save
flash[:notice] = "Successfully created photos."
redirect_to :back
else
render :action => 'new'
end
end
def edit
#photo = Photo.find(params[:id])
end
def update
#photo = Photo.find(params[:id])
if #photo.update_attributes(paramas[:photo])
flash[:notice] = "Successfully updated photo."
redirect_to #photo.gallery
else
render :action => 'edit'
end
end
def destroy
#photo = Photo.find(params[:id])
#photo.destroy
flash[:notice] = "Successfully destroyed photo."
redirect_to #photo.gallery
end
end
User model:
# It is setup so no gallery is created, and photos are associated with the user.
private
def setup_gallery
Gallery.create(user: self)
end
Photo model:
attr_accessible :title, :body, :gallery_id, :name, :image, :remote_image_url
belongs_to :gallery
has_many :gallery_users, :through => :gallery, :source => :user
belongs_to :user
mount_uploader :image, ImageUploader
LIMIT = 5
validate do |record|
record.validate_photo_quota
end
def validate_photo_quota
return unless self.user
if self.user.photos(:reload).count >= LIMIT
errors.add(:base, :exceeded_quota)
end
end
end
You could set up the user model to be linked directly to a default photo.
class User < ActiveRecord::Base
belongs_to :default_photo, :class_name => "Photo"
end
You'd also need to add a default_photo_id column to the users table.
Then provide an interface that allows the user to browse all of their photos. In the UI you could have a button that says "Make default" (or whatever), and when the user clicks on that button it triggers a controller action that looks something like this:
def choose_default_photo
#photo = Photo.find params[:photo_id]
current_user.default_photo = #photo
redirect_to '/profile' # or wherever you wan to send them
end
Then whenever you need to reference the model for the default photo you'd just use:
current_user.defaut_photo
You should also take care of scenario when you destroy the default image . you should set default_photo_id to nil or to any other photo if you want.
I am using CarrierWave and as of now the gallery is open to the public with no ownership. I want to setup so that for one, the user does not have to create a Gallery. The only option should be to upload photos to their account and I want to limit each user photo uploads to 5 maximum. So if User 16 signs in, they have option to upload up to 5 photos to their profile. Once that limit is reach, if the user tries to upload more it should say "Maximum photos uploaded, delete to upload more". I'm not sure exactly how to pull this off.
photo.rb model:
class Photo < ActiveRecord::Base
attr_accessible :title, :body, :gallery_id, :name, :image, :remote_image_url
has_many :user, :through => :gallery
has_many :gallery
mount_uploader :image, ImageUploader
LIMIT = 5
validate do |record|
record.validate_photo_quota
end
def validate_photo_quota
return unless self.user
if self.gallery.user(:reload).count >= LIMIT
errors.add(:base, :exceeded_quota)
end
end
end
photo controller:
class PhotosController < ApplicationController
def new
#photo = Photo.new(:gallery_id => params[:gallery_id])
end
def create
#photo = Photo.new(params[:photo])
if #photo.save
flash[:notice] = "Successfully created photos."
redirect_to #photo.gallery
else
render :action => 'new'
end
end
def edit
#photo = Photo.find(params[:id])
end
def update
#photo = Photo.find(params[:id])
if #photo.update_attributes(paramas[:photo])
flash[:notice] = "Successfully updated photo."
redirect_to #photo.gallery
else
render :action => 'edit'
end
end
def destroy
#photo = Photo.find(params[:id])
#photo.destroy
flash[:notice] = "Successfully destroyed photo."
redirect_to #photo.gallery
end
end
galleries controller:
class GalleriesController < ApplicationController
def index
#galleries = Gallery.all
end
def show
#gallery = Gallery.find(params[:id])
end
def new
#gallery = Gallery.new
end
def create
#gallery = Gallery.new(params[:gallery])
if #gallery.save
flash[:notice] = "Successfully created gallery."
redirect_to #gallery
else
render :action => 'new'
end
end
def edit
#gallery = Gallery.find(params[:id])
end
def update
#gallery = Gallery.find(params[:id])
if #gallery.update_attributes(params[:gallery])
flash[:notice] = "Successfully updated gallery."
redirect_to gallery_url
else
render :action => 'edit'
end
end
def destroy
#gallery = Gallery.find(params[:id])
#gallery.destroy
flash[:notice] = "Successfully destroy gallery."
redirect_to galleries_url
end
end
Restricting user access
To restrict user access to certain models I would use something like CanCan.
It would let you do stuff like this:
## ability.rb
# Allow user to CRUD pictures belonging to own gallery
can :manage, Picture, gallery: {user: user}
In the controller you can then do stuff like this:
# picture_controller.rb
# assuming a nested route, e.g. galleries/1/pictures
load_and_authorize_resource :gallery
load_and_authorize_resource :picture, through: :gallery
This will make sure that each user only sees his or her own pictures.
Restricting number of pictures in gallery
I think your approach with the validation is okay.
I would simplify it thus:
validate :quota
private
def quota
return unless user
if gallery.pictures.count > 4
errors[:base] << "Maximum photos uploaded, delete to upload more"
end
end
The error message should probably go into a locale file.
Creating Gallery automatically for each user
To do this, make sure that the Gallery model has a belong_to association to User. Then create the gallery in a callback in the User model:
# models/user.rb
after_create :setup_gallery
private
def setup_gallery
Gallery.create(user: self)
end
General notes
When you define your has_many relations, you should use plural names, like has_many :users or has_many :galleries.