Question

I have Sportists with multiple disciplines and each discipline has one record. I'd like to display the record and in db they are saved as m100rec, m200rec and so on. Is there a way I could display them like so:

@discipline + "rec" ? I have saved @discipline in my Controller as an instance variable that contains the session value and that session has the discipline name saved in it.

EDIT

The view as it goes:

<% @sportists.each do |s| %>
 <%= s.m100rec %>
<% end %>

and since there are many disciplines which are all named by the same convention of 'discipline' + 'rec' I would like to make the code more readable and DRY and use just <%= s.discipline+'rec' %> somehow.

Was it helpful?

Solution

You can use:

<% @sportists.each do |s| %>
  <%= s.send("#{@discipline}rec") %>
<% end %>

Or

<% @sportists.each do |s| %>
  <%= s.attributes["#{@discipline}rec"] %>
<% end %>
  • The first will work if m100rec is a field, method or association.
  • The second will only work if m100rec is a field, but I think it's clearer what the code is doing.

A better way to structure the relation between Sportists and discipline records might be with a join table?

class Sportist < ActiveRecord::Base
  has_many :sportist_disciplines
  has_many :disciplines, :through => :sportist_disciplines
  ...
end

class SportistDiscipline < ActiveRecord::Base
  belongs_to :sportist
  belongs_to :discipline
  ...
end

class Discipline < ActiveRecord::Base
  has_many :sportist_disciplines
  has_many :sportists, :through => :sportist_disciplines
  ...
end

You could then have a field for record in the sportist_disciplines table, and look it up with -

In the controller:

@sportists = Sportist.includes(:sportist_disciplines).where( ... )
@discipline = Discipline.where( ... ).first

In the view:

 <% @sportists.each do |s| %>
   <%= s.sportist_disciplines.where(:discipline => @discipline).record %>
 <% end %>

N.B: This is only a suggestion for the 'rails-y' way to do this - it might not be suitable depending on the rest of the application and/or the source of the data.

OTHER TIPS

@discipline.map{|e| e + "rec"}

I think you are looking for something like this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top