ruby on rails - Return list based on has_many relationship -


a state can have many units. unit can have 1 state.

on home page want return list of states have units. right listed name.

so if arizona , colorado ones units...they show on home page.

i'm new rails , i've searched , searched. but, i'm missing something. seems sort of query or filter on controller? returning states have units? appreciated.

static page controller    def home    @units = unit.all    @states = state.order('long_name')   end    home view  <% @states.each |state| %> <%= link_to state.long_name, state %> <% end %> 

join should enough:

@states = state.joins(:units).order('states.long_name asc') 

or, can move model scopes:

scope :with_units, joins(:units).order('states.long_name asc') 

and call in controller with:

@states = state.with_units 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -