나는 Sportists
여러 분야를 가지고 있으며 각 분야에는 하나의 record
. 나는 기록을 표시 할 및 DB에 그들로 저장됩니다 m100rec
, m200rec
등등. 다음과 같이 표시 할 수있는 방법이 있습니까?
@discipline + "rec"
? 값 을 포함하는 인스턴스 변수로 저장 @discipline
했으며 해당 세션에는 분야 이름이 저장되어 있습니다.Controller
session
편집하다
보기 :
<% @sportists.each do |s| %>
<%= s.m100rec %>
<% end %>
그리고 'discipline'+ 'rec'의 동일한 규칙으로 명명 된 많은 분야가 있기 때문에 코드를 더 읽기 쉽고 DRY하고 <%= s.discipline+'rec' %>
어떻게 든 사용하고 싶습니다 .
당신이 사용할 수있는:
<% @sportists.each do |s| %>
<%= s.send("#{@discipline}rec") %>
<% end %>
또는
<% @sportists.each do |s| %>
<%= s.attributes["#{@discipline}rec"] %>
<% end %>
m100rec
필드, 방법 또는 연관 인 경우 작동합니다 .m100rec
필드 인 경우에만 작동 하지만 코드가 수행하는 작업이 더 명확하다고 생각합니다.Sportists
조인 테이블을 사용하는 것이 및 분야 레코드 간의 관계를 구조화하는 더 좋은 방법 일까요?
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
그런 다음 테이블 record
에 대한 필드를 가질 수 sportist_disciplines
있으며-
컨트롤러에서 :
@sportists = Sportist.includes(:sportist_disciplines).where( ... )
@discipline = Discipline.where( ... ).first
보기에서 :
<% @sportists.each do |s| %>
<%= s.sportist_disciplines.where(:discipline => @discipline).record %>
<% end %>
NB : 이는 'rails-y'방식에 대한 제안 일뿐입니다. 나머지 애플리케이션 및 / 또는 데이터 소스에 따라 적합하지 않을 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다