【问题标题】:Nested Model not saving on Initial create嵌套模型未在初始创建时保存
【发布时间】:2015-06-04 12:44:42
【问题描述】:

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

我的对象及其关联:

事件 has_one 时间表

安排belongs_to_event has_many Days

天属于_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>

部分天数:

<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

如您所见,由于某种原因,它没有保存参数几天。

【问题讨论】:

  • 你的 event_params 方法在哪里?可能是强参数的问题。
  • 请张贴form代码。
  • @Pavan 我更新了表单代码,但我认为问题一定出在我处理计划模型的方式上,因为如果我稍后编辑它一切正常,而不是在初始创建时。

标签: ruby-on-rails ruby


【解决方案1】:

所以我发现删除这条线

@schedule = @event.create_schedule(event_id: @event.id, user_id: current_user.id)

create 方法解决了这个问题。我想因为我已经使用@event 参数和嵌套形式保存它,所以这个额外的创建方法中断了它。

显然,我在使用 Rails 方面还有很多东西要学。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多