Has_one association must have "only" one association

I have a User and Gallery model, as well as the following associations:

gallery.rb

attr_accessible :name, :description belongs_to :user 

user.rb

 has_one :gallery 

The gallery is created through the form and is not built on the creation of the user (I do this because some users are not allowed to create the gallery)

Here is the gallery controller with the create action:

galleries_controller.rb

 def create @gallery = Gallery.new(params[:gallery]) @gallery.user_id = current_user.id # save user_id to gallery if @gallery.save redirect_to @gallery, :notice => "Your gallery has been successfully created." else render :action => 'new' end end 

1.) My first question is:

when I set up a 1-to-1 association like this, the user can create as many galleries as he wants. Doesn't that really have โ€œonlyโ€ one association? (I donโ€™t think I understood this concept. Why is there no mistake?)

2.) My second question:

To have only one gallery for the user, I had a check for user_id in the gallery model

 validates :user_id, :uniqueness => true 

Is it right to avoid many gallery entries associated with a single user?

EDIT

Thanks to Rubin, I do it like this:

controller

 def new if current_user.gallery == nil @gallery = current_user.build_gallery else flash[:error] = "You already have a gallery" end end def create @gallery = current_user.build_gallery(params[:gallery]) if @gallery.save redirect_to @gallery, :notice => "Your gallery has been successfully created." else render :action => 'new' end end 

In view (new.html.erb)

 <% if current_user.gallery == nil %> <%= form ... %> <% end %> 

No need to check user_id

+4
source share
3 answers

You can put a check in a new action to find out if the user already has a gallery and redirect the user, indicating that they already have a gallery, or to warn the user that creating a new gallery will destroy their existing one. In the latter case, you will also need to check the existing gallery in the create action and delete it before saving the new one, otherwise you will have bottomless galleries populating your database.

In your submissions, you can check them and show only the new link if the user does not have a gallery.

+3
source

Repeat your first question: what has_one really does is that it adds the LIMIT 1 to the corresponding sql query and nothing more. That is why, in your case, the user can create as many galleries as he wants.

+4
source

To answer the second question, you can set a unique true value for your migration, which creates a foreign key:

add_index: gallery ,: user_id, unique: true

0
source

Source: https://habr.com/ru/post/1385891/


All Articles