2013-09-25 39 views
0

我在獲取「更新表單」以顯示嵌套屬性時遇到了一些困難。具體而言,顯示圖像(例如,「選擇」)。所有其他數據字段正在顯示。只是這是不是我的方式:Rails - 以「更新」形式顯示嵌套屬性

<%= bootstrap_form_for @template, :url => {:action => 'update', :id => @template.id } do |f| %> 
<fieldset> 
    <legend>Update Your Template</legend> 
    <%= f.text_field :prompt, :class => :span6, :placeholder => "Which one is running?", :autocomplete => :off %> 
    <%= f.select 'group_id', options_from_collection_for_select(@groups, 'id', 'name', selected: @template.group.id) %> 
    <div class="row-fluid"> 
    <ul class="thumbnails"> 
     <%= f.fields_for :template_assignments do |builder| %> 
     <li class="span3" id=""> 
     <div class="thumbnail"> 
      <%= builder.text_field :choice_id %> 
      <%= image_tag @template.template_assignments.builder.choice.image %> 
     </div> 
     </li> 
     <% end %> 
    </ul> 
    </div> 
<% end %> 

我遇到問題的主線是:

<%= image_tag @template.template_assignments.builder.choice.image %>

我不能讓它通過每個對圖像的4個嵌套屬性的迭代。它迭代了與choice_id有關的4個嵌套屬性,這些屬性在text_field中正確顯示。

如果我將其更改爲:

<%= image_tag @template.template_assignments.first.choice.image %>,它顯示第一圖像沒有問題。但是,我需要它迭代並顯示「第一個」,「第二個」,「第三個」和「第四個」圖像。

如何顯示這些圖像的任何幫助,就像顯示image_id的?

編輯: 這裏是我的模型

# app/models/template.rb 

class Template < ActiveRecord::Base 
belongs_to :group 
has_many :template_assignments, dependent: :destroy 
has_many :choices, :through => :template_assignments 
accepts_nested_attributes_for :template_assignments, allow_destroy: true 
end 

 

# app/models/template_assignment.rb 

class TemplateAssignment < ActiveRecord::Base 
belongs_to :template 
belongs_to :choice 
end 

 

# app/models/choice.rb 

class Choice < ActiveRecord::Base 
    has_many :template_assignments 
    has_many :templates, :through => :template_assignments 
end 

回答

1

你可能會想只是使用builder直接,就像你在做text_field

<%= image_tag builder.choice.image %> 

[更新]一些試驗後和錯誤的正確形式是:

<%= image_tag builder.object.choice.image %> 

發生了什麼事是,當f.fields_for :template_assignments do |builder|被用來渲染嵌套項目,該builder對象是yield版到該塊不是對象本身(在本例中爲TemplateAssignment),而是FormBuilder對象,它提供了像builder.text_field這樣的便利方法。 (如果您嘗試執行template_assignment.text_field,您會看到一個錯誤。)builderobject的形式存儲它所代表的對象,因此您可以使用builder.object來保留template_assignment對象。從那裏你可以像正常一樣處理template_assignment。我希望有所幫助。

+0

謝謝傑里米。但是這不起作用。我不知道這是否是因爲「choice.image」完全在它自己的表格中。我更新了OP以顯示我的模型。 – Dodinas

+0

更具體地說,當我使用你的建議時,我得到以下錯誤:''NoMethodError:undefined method'choice'「' – Dodinas

+0

也許試試'<%= image_tag builder.object.choice.image%>'? –