2012-11-15 9 views
0

내 뷰에서 호출 할 때 왜 테이블을 생성하지 않습니까? fields_table (@user, [ "id", "username"])을 사용하면 tbody의 trs 또는 tds를 얻지는 못하지만 다른 모든 것은 얻고 있습니다.Ruby on Rails에서 테이블 생성

def fields_table(obj, fields) 
    return false if obj.nil? 
    content_tag(:table) do 
    thead = content_tag(:thead) do 
     content_tag(:tr) do 
     content_tag(:td, "Property") + content_tag(:td, "Value") 
     end 
    end 
    tbody = content_tag(:tbody) do 
     fields.each do |name| 
     content_tag(:tr) do 
      content_tag(:td, name) + content_tag(:td, obj.read_attribute(name)) 
     end 
     end 
    end 
    thead + tbody 
    end 
end 

답변

0

이 코드는 필드를 반복합니다. 그것은 아무 것도 반환하지 않으므로 동봉 한 tbody은 내용에 아무 것도 가지지 않을 것입니다.

tbody = content_tag(:tbody) do 
    fields.map do |name| 
    content_tag(:tr) do 
     content_tag(:td, name) + content_tag(:td, obj.read_attribute(name)) 
    end 
    end.join 
end 
+0

하지만에만 TBODY한다. 내가 디버깅하려하지만 어쩌면 왜 그런지 알아? – Dave

+0

구글 "html_safe", 어딘가에는 신뢰할 수없는 문자열이 있으므로 더 이상 안전하게 표시 할 수 없습니다. 해당 메소드에 ".html_safe"를 추가하고 거기에서부터 수정하여 문제를 해결할 수 있습니다. –

0

내가 수집 인수를 사용하여 부분 렌더링 추천, 내장 :

tbody = content_tag(:tbody) do 
    fields.each do |name| 
    content_tag(:tr) do 
     content_tag(:td, name) + content_tag(:td, obj.read_attribute(name)) 
    end 
    end 
end 

당신은 당신이 같은 코드의 다른 부분에서 뭔가를 반환하거나 같은 것을로 변경해야 이러한 유형의 작업을 수행하는 레일의 장점. 테이블 표제가 들판과 일렬로 정렬되기를 바랍 니? 당신은 여전히 ​​다음의 행을 따라 무엇인가 할 수 있습니다. (테스트는 끝났지 만 작동합니다.)

모델에서 프런트 엔드에 표시하려는 속성을 포함하는 상수로 클래스 메서드 또는 배열을 정의합니다.

모델/user.rb

VisibleFields = [:id, :username] 

#workaround for toplevel class constant warning you may get 
def self.visible_fields 
    User::VisibleFields 
end 

보기/사용자/html로 이스케이프되는 몇 가지 이유를 들어 index.html.erb

<table> 
    <thead> 
    <tr> 
    <% User.visible_fields.each do |field| %> 
     <th><%= field.to_s.titleize %></th> 
    <% end %> 
    </tr> 
    </thead> 
<tbody> 
<%= render :partial => 'user', :collection => @users %> 
</tbody> 
</table> 

**views/users/_user.html.erb** 

<tr> 
<% user.visible_fields.each do |field| %> 
    <td class="label"><%= field.to_s.titleize %></td><td class="value"><%= user.send(:field) %></td> 
<% end %> 
</tr> 
관련 문제