2015-03-12 3 views
0

У меня возникли проблемы с вложением вложенной формы в rails 4.2.0 и ruby ​​2.2.0. Я вернулся и попытался следовать the Railscast from 2010, но даже после этого примера мои подполя не отображаются. Что я делаю не так? Есть ли новая передовая практика для вложенных форм сейчас?Вложенные формы моделей (accepts_nested_attributes_for) в Rails 4.2.0: подполе не отображаются

просмотров/обзоры/_form.html.erb:

<%= form_for(@survey) do |f| %> 
    ... 
    <% f.fields_for :questions do |builder| %> 
     <div class="field"> 
      <%= builder.label :content, 'Question' %><br> 
      <%= builder.text_area :content, rows: 3 %> 
     </div> 
    <% end %> 
    ... 
<% end %> 

Контроллеры/survey_controller.rb

class SurveysController < ApplicationController 
    before_action :set_survey, only: [:show, :edit, :update, :destroy] 
    ... 
    # GET /surveys/new 
    def new 
    @survey = Survey.new 
    3.times { @survey.questions.build } 
    end 
    ... 
    private 
    ... 
    # Never trust parameters from the scary internet, only allow the white list through. 
    def survey_params 
     params.require(:survey).permit(:name, questions_attributes:[:content]) 
    end 
end 

модели/questions.rb

# == Schema Information 
# 
# Table name: questions 
# 
# id   :integer   not null, primary key 
# survey_id :integer 
# content :text 
# created_at :datetime   not null 
# updated_at :datetime   not null 
# 

class Question < ActiveRecord::Base 
    belongs_to :survey 
end 

модели/surveys.rb

# == Schema Information 
# 
# Table name: surveys 
# 
# id   :integer   not null, primary key 
# name  :string 
# created_at :datetime   not null 
# updated_at :datetime   not null 
# 

class Survey < ActiveRecord::Base 
    has_many :questions, dependent: :destroy 
    accepts_nested_attributes_for :questions 
end 

Я предполагаю, что это что-то простое, но я потратил слишком много времени, пытаясь понять это. Кто-нибудь знает, почему мои поля не появляются?


Решение:

Я забыл оказывать подполя (<% вместо <% =). Правильный текст в _form.rb должен быть:

<%= f.fields_for :questions do |builder| %> 
     <div class="field"> 
      <%= builder.label :content, 'Question' %><br> 
      <%= builder.text_area :content, rows: 3 %> 
     </div> 
    <% end %> 

ответ

1

Вы должны иметь <%= на вашем fields_for

<%= f.fields_for :questions do |builder| %> 
    <div class="field"> 
     <%= builder.label :content, 'Question' %><br> 
     <%= builder.text_area :content, rows: 3 %> 
    </div> 
<% end %> 
+0

Спасибо, что решил его! Я знал, что это была простая вещь, которую мне не хватало. Я приму этот ответ, когда сайт позволит мне. – Lee

 Смежные вопросы

  • Нет связанных вопросов^_^