相关疑难解决方法(0)

Rails 4:fields_for中的fields_for

我正在学习RoR,我正在尝试找到如何使用has_one模型在另一个中设置fields_for:

class Child < ActiveRecord::Base
    belongs_to :father
    accepts_nested_attributes_for :father
end

class Father < ActiveRecord::Base
    has_one :child
    belongs_to :grandfather
    accepts_nested_attributes_for :grandfather
end


class Grandfather < ActiveRecord::Base
    has_one :father
end
Run Code Online (Sandbox Code Playgroud)

我在Railscasts上使用嵌套模型表单第1部分来获取这些:在children_controller.rb中:

  def new
    @child = Child.new
    father=@child.build_father
    father.build_grandfather
  end

def child_params
      params.require(:child).permit(:name, father_attributes:[:name], grandfather_attributes:[:name])
    end
Run Code Online (Sandbox Code Playgroud)

我的形式:

<%= form_for(@child) do |f| %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  mother:<br>
  <%= f.fields_for :father do |ff| %>
    <%= ff.label :name %>
    <%= ff.text_field :name %><br>
      grand mother:<br>
      <%= f.fields_for :grandfather …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails form-for fields-for nested-form-for ruby-on-rails-4

15
推荐指数
1
解决办法
2万
查看次数

Rails 4嵌套属性不保存

我似乎无法获得嵌套属性来保存到数据库.我正在使用Rails 4.

这是我的模特:

class Answer < ActiveRecord::Base
  belongs_to :question
end


class Question < ActiveRecord::Base
  has_many :answers
  belongs_to :survey
  accepts_nested_attributes_for :answers, allow_destroy: true
end

class Survey < ActiveRecord::Base
  has_many :questions
  validates_presence_of :name
  accepts_nested_attributes_for :questions
end
Run Code Online (Sandbox Code Playgroud)

这是控制器:

def create

  @survey = Survey.new(survey_params)

  respond_to do |format|
    if @survey.save
      format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
      format.json { render action: 'show', status: :created, location: @survey }
    else
      format.html { render action: 'new' }
      format.json { render json: @survey.errors, status: :unprocessable_entity } …
Run Code Online (Sandbox Code Playgroud)

ruby ruby-on-rails nested-forms ruby-on-rails-4

11
推荐指数
1
解决办法
2万
查看次数