嵌套模型未保存在初始创建

时间:2015-06-04 03:00:23

标签: ruby-on-rails ruby

我有一个双嵌套模型“days”,最初不会保存,但在我之后编辑记录时会保存。我相信这是由于我如何在第一个模型控制器中创建第二个模型“计划”

我的对象及其联想:

事件has_one Schedule

计划belongs_to_event has_many天

Days belongs_to Schedule

我想与事件一起自动创建日程表,有没有办法正确地执行此操作,或者这只是不好的做法,我应该以不同的方式尝试这个吗?

   class EventsController < ApplicationController

  before_action :set_event, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [ :show ]

  def index
    @events = current_user.events.all
  end

  def show
  end

  def new
    @event = current_user.events.build
    @schedule = @event.build_schedule(event_id: @event.id, user_id: current_user.id, )

  end

  def edit
    if @event.user_id != current_user.id
      flash[:error] = "Not allowed"
      redirect_to root_path
    else
      @schedule = @event.schedule
    end

  end

  # POST /events
  # POST /events.json
  def create
    @event = current_user.events.create(event_params)
    @schedule = @event.create_schedule(event_id: @event.id, user_id: current_user.id)



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

  def update
    if @event.user_id == current_user.id
      respond_to do |format|
        # puts "call sanitize_url"
        # sanitize_url
        if @event.update(event_params)
          format.html { redirect_to @event, notice: 'Event was successfully updated.' }
          format.json { render :show, status: :ok, location: @event }
        else
          format.html { render :edit }
          format.json { render json: @event.errors, status: :unprocessable_entity }
        end
      end
    else
      flash[:error] = "Not allowed"
      redirect_to root_path
    end
  end

  # DELETE /events/1
  # DELETE /events/1.json
  def destroy
    if @event.user_id == current_user.id
      @event.destroy
      respond_to do |format|
        format.html { redirect_to events_url, notice: 'Event was successfully destroyed.' }
        format.json { head :no_content }
      end
    else
      flash[:error] = "Not allowed"
      redirect_to root_path
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_event
      @event = Event.find(params[:id])
    end

    def event_params
      params.require(:event).permit(
        :name, :description, 
        links_attributes: [:id, :label, :url, :_destroy], 
        schedule_attributes: [:id, :_destroy, days_attributes: [:id, :date, :_destroy]]
        )
    end


end

表格代码:(我正在使用Cocoon作为嵌套表格。)

<%= simple_form_for(@event) do |f| %>
<%= f.error_notification %>

<div class="form-inputs">
    <%= f.input :name %>
    <%= f.input :description %>
    <hr>
</div>

<div>
    <button type="button" class="btn schedbtn btn-default btn-block">Event Schedule</button>

    <div class="collapse">
        <br>
        <%= f.simple_fields_for :schedule do |schedule| %>
            <%= render 'schedule_fields', f: schedule %>
        <% end %>
    </div>
    <hr>
</div>

<script>
    $(document).ready(function(){
        $(".schedbtn").click(function(){
            $(".collapse").collapse('toggle');
        });
    });
</script>

<div class="nested-fields">
    <%= f.simple_fields_for :links do |link| %>
        <%= render 'link_fields', f: link %>
    <% end %>
</div>
<div class="links">
    <%= link_to_add_association 'Add Link', f, :links, class: "btn btn-block btn-default add-buton" %>
</div>

<div class="form-actions" style="padding: 0px 0px 15px 0px;">
    <hr>
    <%= f.button :submit %>

    <%= link_to 'Back', events_path, class: "btn btn-default", style: "margin-left: 10px;" %>
</div>

安排部分:

<p><%= @event.schedule.id %></p>
<p><%= @schedule %><%= @schedule.id %></p>
<div class="links">
    <%= link_to_add_association 'Add Day', f, :days, class: "btn btn-block btn-default add-buton" %>
</div>
<div class=" nested-fields">
    <%= f.simple_fields_for :days do |day| %>
        <%= render 'day_fields', f: day %>
    <% end %>
</div>

Days Partial:

<div class="nested-fields">
<%= f.input :date, input_html: { class: "form-input form-control" } %>
<%= link_to_remove_association "Remove", f, class: "form-button btn btn-default" %>
<hr>

这是初始提交期间的服务器输出:

SQL (0.5ms)  INSERT INTO "schedules" ("user_id", "created_at", "updated_at") VALUES (?, ?, ?)  [["user_id", 1], ["created_at", "2015-06-04 02:34:38.724966"], ["updated_at", "2015-06-04 02:34:38.724966"]]
   (4.5ms)  commit transaction
   (0.1ms)  begin transaction

Day Load (0.2ms)  SELECT "days".* FROM "days" WHERE "days"."schedule_id" = ?  [["schedule_id", 31]]
  SQL (0.4ms)  DELETE FROM "days" WHERE "days"."id" = ?  [["id", 24]]
  SQL (0.2ms)  DELETE FROM "schedules" WHERE "schedules"."id" = ?  [["id", 31]]
   (1.5ms)  commit transaction

正如您所看到的那样,由于某种原因,它不会将参数保存几天。

1 个答案:

答案 0 :(得分:0)

所以我想出了删除这一行

@schedule = @event.create_schedule(event_id: @event.id, user_id: current_user.id)
from create方法修复了问题。我想因为我已经使用@event params和嵌套表单保存它,这个额外的create方法会中断它。

显然我还有很多需要学习的东西。