How can I make it so that an organization is only created if the user is NOT signed in?
That’s a little vague, so let me make that a little clearer. I have two tables; one organization table, and another user table. Organizations has many users, and users belong to an organization.
# models/organizations.rb
class Organization < ActiveRecord::Base
has_many :users
I made it so that when a user signs up, an organization is created along with his account.
# models/user.rb
class User < ActiveRecord::Base
belongs_to :organization
before_create :create_organization
private
def create_organization
self.organization = Organization.create :name => self.name
end
Cool, that works.
But users should also be able to sign other people up for an account, and that new user’s organization_id should be the same as current_user.organization_id
*# controllers/users_controller.rb*
def create
@user = User.new(params[:user])
if current_user
@user.organization_id = current_user.organization_id
end
end
This solution is limiting me, because the model is creating an organization even if the user is already signed in. They work independently (if I take out either the before_filter in the model or the if current_user in the controller), but not together.
I’m having a difficult time making them work together because you can’t access current_user in the user model.
I’d put the organization_id as a paramater in the sign up link, but that’s not very secure as that means any user could simply change the organization_id in the URL and automatically get an account to another organization that doesn’t belong to them.
If it matters, I’m using Authlogic as my authentication solution.
Is there anything I can do in the user model or the user controller to accomplish this?
Just check if
organizationis present in thebefore_filter:If a user is signed in, the new user will be associated with an organization already and the
before_filterwill not create a new one.