簡體   English   中英

如何從父控制器保存子記錄?

[英]How do I save my child records from the parent controller?

我已經保存了一堆“孩子”對象,我想創建一個父對象,該對象通過“相對”模型鏈接到孩子。

這個對象通過親戚給了我很多對很多。

明確說明:用戶訪問“父母”頁面,單擊“創建父母”,並顯示一個表單,該表單可讓他們命名父母並為該父母添加最多四個孩子(通過創建“親戚”),每個“親戚” ”也被命名-這是重要的部分。 因此,例如,我可以將關系命名為“繼子”或“兒子”。

這是我到目前為止的代碼:

class Kid < ActiveRecord::Base
  has_many :relatives
  has_many :parents, through: :relatives
end


class Parent < ActiveRecord::Base
  has_many :relatives
  has_many :kids, through: :relatives

  accepts_nested_attributes_for :relatives,
    :reject_if => lambda { |a| a[:content].blank? },
    :allow_destroy => true
end


class Relative < ActiveRecord::Base
  belongs_to :parent
  belongs_to :kid
end



class ParentsController < ApplicationController
  before_action :set_parent, only: [:show, :edit, :update, :destroy]
  before_action :lookup_kids, only: [:new, :edit]

  # GET /parents
  # GET /parents.json
  def index
    @parents = Parent.all
  end

  # GET /parents/1
  # GET /parents/1.json
  def show
  end

  # GET /parents/new
  def new    
    @parent = Parent.new
    4.times { @parent.relatives.build }
  end

  # GET /parents/1/edit
  def edit
  end

  # POST /parents
  # POST /parents.json
  def create
    @parent = Parent.new(parent_params)        

    parent_params[:relatives_attributes].each do |k,r|
      @parent.relatives.build(r.except(:_destroy))
    end

    respond_to do |format|
      if @parent.save
        format.html { redirect_to @parent, notice: 'Parent was successfully created.' }
        format.json { render :show, status: :created, location: @parent }
      else
        format.html { render :new }
        format.json { render json: @parent.errors, status: :unprocessable_entity }
      end
    end
  end

  # cut for brevity.



  private

    # Use callbacks to share common setup or constraints between actions.
    def set_parent
      @parent = Parent.find(params[:id])
    end


    def parent_params
      params.require(:parent).permit(:name,
       relatives_attributes: [:parent_id, :kid_id, :relationship, :_destroy])
    end
    def lookup_kids
      @kids = Kid.all #for this nursery.
    end
end





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

      <% @parent.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>

  <h4>Kids:</h4>
  <%= f.fields_for :relatives do |r| %>
    <%= r.label :kid %>
    <%= r.collection_select :kid_id,
      @kids, :id, :name, include_blank: true%>
    <%= r.label :relationship %>
    <%= r.text_field :relationship %>    
    <%= r.check_box :_destroy %>
    <%= r.label :_destroy, "Remove" %>
    <br/>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>



ActiveRecord::Schema.define(version: 20151030113634) do
  create_table "kids", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
  create_table "parents", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
  create_table "relatives", force: :cascade do |t|
    t.string   "relationship"
    t.integer  "parent_id"
    t.integer  "kid_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end
  add_index "relatives", ["kid_id"], name: "index_relatives_on_kid_id"
  add_index "relatives", ["parent_id"], name: "index_relatives_on_parent_id"
end

當我在父控制器中進行“創建”時,可以看到正確的參數通過了,但是關系記錄沒有保存。 這不是應該自動發生嗎?

我嘗試遍歷:relatives_attributes,但是似乎不適用於'build'。

我該如何保存“親戚”記錄以保存?

編輯:添加參數發布:

parent"=>{
  "name"=>"Dad",
  "relatives_attributes"=>{
     "0"=>{"kid_id"=>"2", "relationship"=>"Son", "_destroy"=>"0"},
     "1"=>{"kid_id"=>"", "relationship"=>"", "_destroy"=>"0"},
     "2"=>{"kid_id"=>"", "relationship"=>"", "_destroy"=>"0"},
     "3"=>{"kid_id"=>"", "relationship"=>"", "_destroy"=>"0"}}}

編輯:我已經更新了它以顯示我的最新編輯-請注意'parent_params [:relatives_attributes] .each do | k,r |' 在控制器中。 現在可以保存孩子的記錄,但是唯一的問題是,它還可以保存空白的字段! 所以我有孩子記錄的空值的“相對”記錄。 如何停止保存空白字段(或創建空白的相對記錄)?

答案是建立相對的每個子記錄,如下所示:

parent_params[:relatives_attributes].each do |k,r|
  @parent.relatives.build(r.except(:_destroy))
end

在調用@ parent.save之前。

但是,我仍然有擺脫空白記錄的問題。 因此,如果有人對這個問題有答案,請在這里評論-或如果有更好或更傳統的方式來解決這個問題,請打我。 在此跟進問題: 為什么我的模型中的這個reject_if不拒絕空白記錄?

您幾乎就在那兒,具體取決於表單提交的方式,您最有可能在您的相對關聯類中也需要一個accepts_nested_attribute_for:

class Relative
  belongs_to :parent
  accepts_nested_attributes_for :parent
  belongs_to :kid 
  accepts_nested_attributes_for :kid
end

如果這不起作用,那么請提交您傳遞給控制器​​的參數,我們可以相應地進行調整

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM