Raghvendra Parashar
Raghvendra Parashar

Reputation: 4053

ROR : what is the best way to populate data in select box

Ruby on Rails : what is the best way to populate data in select box

as explained here

select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: 'None'})

But best practices says that don't query for data from view

here Person.all will place a query to get all persons

please justify this Person.all calling from view

Upvotes: 0

Views: 143

Answers (3)

Sachin Singh
Sachin Singh

Reputation: 7225

don't fetch all attributes of the object instead use select clause like

Person.select('id,name').map{|person| [person.id, person.name]}, and off-course interact 

with your database like (controller <=> model <=> Database), as per MVC architecture.

Upvotes: 2

Christoph Eicke
Christoph Eicke

Reputation: 1144

You are right, don't query data in a view. Better would be to prepare an instance variable in the controller and pass it to the view. But I think this is really debatable here since it's such a minor thing. When you have it in the view like this, you don't have to go back to the controller to find out what the instance variable holds, but if you want to stick to conventions, then you are correct and you shouldn't do it.

Upvotes: 5

Justin D.
Justin D.

Reputation: 4976

Why don't you add @people = Person.all in your Controller and then @people.collect { ... } in your view? This way, you will query in your controller and not in your view.

Upvotes: 5

Related Questions