我有兩個模型,Character和Statistic。他們的關係是Character has_one Statistic和Statistic belongs_to Character。Rails:需要幫助在另一個模型視圖中顯示form_for一個模型
我已經爲這兩種模型生成了腳手架,我想要做的就是能夠創建一個新的統計量,如果沒有一個存在,則顯示統計模型並編輯統計模型,全部來自Character視圖。我不確定如何編輯控制器或在視圖中編寫代碼以實現此目的。
這是一些代碼。從人物的看法:
<h2>Statistics</h2>
<%= render "statistics/form" %>
然而,這給了我這個錯誤:
undefined method `build' for nil:NilClass
Extracted source (around line #1):
1: <%= form_for ([@character, @character.statistic.build]) do |f| %>
2: <% if @statistic.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(@statistic.errors.count, "error") %> prohibited this statistic from being saved:</h2>
所以我假設我沒有正確地寫入的第一線?我認爲這會起作用,因爲我希望每個Statistic實例屬於一個Character,並且這會創建這種關係。
下面是從統計/格式的代碼:
<%= form_for ([@character, @character.statistic.build]) do |f| %>
<% if @statistic.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@statistic.errors.count, "error") %> prohibited this statistic from
being saved:</h2>
<ul>
<% @statistic.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :strength %><br />
<%= f.text_field :strength %>
...
<div class="field">
<%= f.label :charisma %><br />
<%= f.text_field :charisma %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
預先感謝任何幫助。我一直在用這種方式與相關模型進行搏鬥大約一週,而我對我還沒有理解感到非常沮喪。
嗯我不認爲這正是我所期待的。我想要做的是在角色和統計之間找到這一關係,然後使用該代碼關聯未來的模型。每個角色也會有技能,專長,裝備等,所以我不想把所有東西都加載到角色形式中。是否可以在角色視圖上顯示統計模型,然後有一個鏈接來編輯將在角色視圖中反映的統計信息?我需要爲此創建一個新的html.erb文件link_to? – illbzo1 2011-05-07 23:53:52
我不知道我在這裏理解你的目標。在爲這些東西生成腳手架之後是否要儘量減少工作?或者你希望能夠以他們自己的形式編輯統計(和其他)?我編輯了答案,向你展示了一種方法。 – 2011-05-08 07:56:05
我實際上都希望這兩種。我絕對想要一種方法來編輯他們自己的形式的統計等,我想保持這些代碼分離,所以角色視圖不會太混亂。你發佈的新方法聽起來好像可能有用,所以我會試一試。謝謝! – illbzo1 2011-05-08 13:21:19