Skip to main content

When to use scoped models?

Rails • Asked by Tang Rufus

In Refactoring CSV Uploads with ActiveModel::Model Download , you make a scoped class User::Import.
When should we use scoped class like this?

And, how does it different from rails generate model user/import?

Thanks!


I'd say any time you're making supporting classes. For example User::Import should be a separate class from User to provide the functionality we want, but at the same time it's really closely tied together with User. That's usually a good sign it deserves being in a module like that.

If you use the generate model functionality, that would actually create a full ActiveRecord object and database table. In this case, I don't need to store the uploaded CSV files, so using an ActiveRecord model isn't necessary. We use ActiveModel::Model to give a regular Ruby class much of the same functionality as an ActiveRecord::Base object would have. That's what makes it easy to create a form_for @user_import.

Make sense?


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.