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
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
source share