user3193550
user3193550

Reputation: 21

Rails polymorphic association - controllers and views?

I have a model User (used for authentication purposes) which is connected to two other models, Customer and Seller via polymorphic association in Rails. A customer and seller must have different sign up forms because of their different data but can use a single login form because they're both Users. In order to manage the customer and seller resources separately, is it a good idea to create respective controllers and views for them, or should management of all Users be done in the UsersController?

Upvotes: 0

Views: 428

Answers (2)

punitcse
punitcse

Reputation: 727

It depends upon the design of the two views customers and sellers. If the design of both the views are different then I will encourage you to create two controllers customers_controller and sellers_controller and you may want to have a module for common actions like lib/authentication.rb.So

# customers_controller.rb
include Authentication
def some_action 
end

and

 # sellers_controller.rb
include Authentication
def other_action 
end

Authentication file like

# lib/authentication.rb
module Authentication
  def common_method
  end
end

You can have two controllers and one module which you can write common methods/actions

Upvotes: 1

Michael Lang
Michael Lang

Reputation: 1038

As @madyrockss pointed out, STI is probably the way to go here because User.find(params[:login]) will return either an instance of Customer or Seller automatically.

I would encourage forgetting about the UsersController and views and encourage thinking in terms of seller and customer controllers/views (that is, don't share a single controller and views per action that can handle either customer or seller and has conditionals within view determining what to show). If the two users have different business rules, the whole thing starts to get messy real quick and becomes unwieldy to manage as business rules change.

For login/logout, if the form is going to be the same for both, then a single controller will suffice and I'd consider a different name than UsersController, such as SessionsController to be more semantically in line with what the controller's purpose is. You are not confined to a one-to-one Models <==> Controllers <==> Views which many beginning Rails developers fall into the trap of.

Upvotes: 0

Related Questions