ruby-on-rails:构建关联对象

时间:2016-01-02 21:07:43

标签: ruby-on-rails

有父母和孩子的模型。我无法理解如何制作这个逻辑:

  1. 如果表格在电子邮件中没有记录,然后以父母表格中的条目形式输入,并且在表格中的сhilds状态字段中记录为真。

  2. 如果表格已在表格字段中输入的电子邮件中有记录сhilds且状态= true,则不要在表格或表格中创建任何新条目父母сhilds

    < / LI>
  3. 如果表格已在表单字段中输入的电子邮件中有记录сhilds且status = false,则会在表格parent中创建一个条目,并在状态字段中创建表格сhilds记录是真的。

  4. 仍然需要能够通过其他形式的控制器ChildsController在表сhilds中创建一个新条目 在表中写入只能创建сhildscurrent_user,其中field status = true。如果在状态字段中成功创建了条目,则写入false

    谢谢。

    migrations parents
    t.string "name"  
    
    migrations childs
    t.string "name" 
    t.string "email"
    t.integer "parent_id"
    t.boolean  "status", default: false
    
    model Parent
    class Parent < ActiveRecord::Base
      has_many :childs
      accepts_nested_attributes_for :childs
    
      validates :name, presence: true, uniqueness: true
    end
    
    model Child
    class Child < ActiveRecord::Base
      belongs_to :parent
    
      validates :name, :email, presence: true
      validates_uniqueness_of :email, scope: :parent
    end
    
    controller ParentsController
    class ParentsController < ApplicationController
      def new
        @parent = Parent.new
        @parent.childs.build
      end
    
      def create
        @parent = Parent.new(parent_params)
        if @parent.save
          redirect_to root_path
        else
          render :new
        end
      end
    
      private
      def parent_params
        params.require(:parent).permit(:name, childs_attributes: [:parent_id, :name, :email, :status])
      end
    
    end
    
    
    form1  to create entries in the tables of parents and childs
    <%= form_for @parent do |parent_form| %>
        <div class="field">
          <%= parent_form.text_field :name %>
        </div><br>
        <%= parent_form.fields_for :childs do |childs_form| %>
            <div class="field">
              <%= childs_form.text_field :name %>
            </div><br>
            <div class="field">
              <%= childs_form.email_field :email %>
            </div><br>
        <% end %>
        <div class="action"><br>
          <%= submit_tag 'submit' %>
        </div>
    <% end %>
    
    
    form2 to create entries in the table childs
    <%= form_for(@child) do |f| %>
        <div class="field">
          <%= f.text_field :name %>
        </div><br>
        <div class="field">
          <%= f.email_field :email %>
        </div><br>
    <div class="action"><br>
      <%= f.submit 'submit' %>
    </div>
    <% end %>
    
    
    controller ChildsController
    class ChildsController < ApplicationController
      def new
        @child = Child.new
      end
    
      def create
        @child = current_user.parent.childs.build(child_params)
        if @child.save
          redirect_to root_path
        else
          redirect_to :back
        end
      end
    
      private
      def child_params
        params.require(:child).permit(:name, :email)
      end
    
    end
    

0 个答案:

没有答案