Ali Sepehri.Kh
Ali Sepehri.Kh

Reputation: 2508

Convert an instance to another type of instance

In ASP.NET, when I want to send a list of model instances to view layer, I convert them into another type (ModelView) by the following code:

var userViewModels = users.select(new {
    Name = Name,
    UserName = Username
});

I do this because I don't want to send all of my user model data (like password) to view layer. I put this code in my business logic Layer.

I'm using AJAX, and I'm sending my data by JSON protocol. What is the best practice in Ruby on Rails to do a similar action?

Upvotes: 0

Views: 81

Answers (2)

Brad Werth
Brad Werth

Reputation: 17647

Although it is probably unnecessary, as dimakura pointed out, you can select arbitrary attributes when finding by using the select method. Your example would end up looking something like:

@users = User.select(:name, :username)

Upvotes: 0

dimakura
dimakura

Reputation: 7655

In RoR you simply pass models to your views.

Also, view in RoR can directly access (though it's not recommended) models from database. So "hiding" models does not make sense here.

You can consider rails generated scaffold as a close to the best practices.

  1. Controller is used for selecting models from database
  2. View is used for rendering model to the user
  3. Model is the main place to store business logic

Upvotes: 1

Related Questions