2014-05-25 24 views
1

詢問在此之前,我已經嘗試與解決方案的詳細here,但沒有奏效。accepts_nested_attributes_for問題表

方面:2種模式,理念和項目。 1個想法屬於1個項目,1個項目有很多想法。 我想創建一個表單創建具有的思想觀念領域,也可以指定他們屬於哪個項目來,通過指示PROJECT_ID場。我與accepts_nested_attributes_for

問題做它:我不能夠創造從形式的新想法時,搶PROJECT_ID。從控制檯我看到一個新的想法得到了保存,但對於PROJECT_ID這個想法總是返回零

代碼:

ideas_controller.rb

# GET /ideas/new 
def new 
@idea = Idea.new 
@idea.build_project 

respond_to do |format| 
format.html # new.html.erb 
format.json { render json: @idea } 
end 

模型> idea.rb

class Idea < ActiveRecord::Base 

belongs_to :project 

accepts_nested_attributes_for :project 

mount_uploader :picture, PictureUploader 
validates :name, presence: true, allow_blank: false 

end 

_form.html.erb

<%= form_for(@idea) do |f| %>  
<% f.fields_for :project do |project_fields| %> 
<% if @idea.errors.any? %> 
<div id="error_explanation"> 
    <h2><%= pluralize(@idea.errors.count, "error") %> prohibited this idea from being saved:  </h2> 

    <ul> 
    <% @idea.errors.full_messages.each do |message| %> 
    <li><%= message %></li> 
    <% end %> 
    </ul> 
</div> 
<% end %> 

<div class="field"> 
<%= f.label :name %><br> 
<%= f.text_field :name %> 
</div> 
<div class="field"> 
<%= f.label :description %><br> 
<%= f.text_area :description %> 
</div> 
<div class="field"> 
<%= f.label :picture %><br> 
<%= f.file_field :picture %> 
</div> 
<div class="field"> 
<%= f.label :project %><br> 
<%= f.number_field :project_id, :class=>"Number" %> 
</div> 
<div class="actions"> 
<%= f.submit %> 
</div> 
<% end %> 
<% end %> 
+0

改變這個'@ idea.build_project'到這一點:'@ idea.project.build'也許會有所幫助。 – matanco

+0

不,它崩潰,並返回一個未定義的方法'建立'nil:編輯行上的NilClass。 – malditojavi

回答

0

根據documentation,「嵌套屬性允許您通過parent」將相關記錄的屬性保存「。你正在通過child這樣做,我認爲這是不可能的。

因此,將accepts_nested_attributes_for移動到父級模型,並使用parent's表單創建parent字段以及child字段。因此您將通過projects_controllerprojects/_form.html.erb

創建projectidea或選擇退出其他任務。

不使用accepts_nested_attributes_for,加project_idsideas PARAMS屬性爲空數組:

def idea_params 
    params.require(:idea).permit(:name, :project_ids => []) 
end 

app/views/ideas/_form.html.erb

<div> 
    <%= idea.label 'File under at least one project' %> 
    <% Project.all.order(name: :asc).each do |project| %> 
    <div> 
     <%= check_box_tag "idea[project_ids][]", project.id %> 
     <%= project.name %> 
    </div> 
</div> 

這個代碼將會給你的項目的複選框選擇。這意味着首先你必須在項目自己的控制器和窗體中分別創建項目。所以你沒有使用嵌套屬性。

相關問題