如何设置列值:使用表单创建新项目时,位置为:项目的ID

时间:2017-11-17 21:55:15

标签: ruby-on-rails

我有一个List控制器/模型/无论你怎么称呼它,当我用表单创建一个新的时,我想将:position列设置为:id。我不知道如何做到这一点。

BTW位置是Integer类型。

我的想法:

  • 在控制器:lists_controller.rb中,在新方法中,或者也许是create方法,添加一些代码。
  • 在设置其他属性时,在表格的某处,潜入那里的小狗。 (我只想在创建新列表时将位置设置为id,而不是更新)
  • 在模型中设置它。 (我不想在我更新/编辑时将:position设置为:id,(仅在创建新项目时),项目,所以我很确定这不会起作用) < / LI>

以下是一些可能有用的代码:

_form.html.erb

<%= form_with(model: @list) do |form| %>
  <div class='addField'>
    <%= form.text_field :name, placeholder: "Name" %>
    <%= form.text_field :description, placeholder: "Description" %>
    <%= form.check_box :private,class: 'check_box' %>
  </div>
  <div class='addLabel'>
    <div>
      <%= form.label :name %>
    </div>
    <div>
      <%= form.label :description %>
    </div>
    <div>
      <%= form.label :private %>
    </div>
  </div>
  <div id='submitNew'>
    <%= form.submit 'Done', :class => 'btn btn-primary' %>
  </div>
<% end %>

lists_controller.rb

class ListsController < ApplicationController

  def new
    @list = List.new
  end

  def create
    @list = List.new(list_params)

    if @list.save
      redirect_to @list
    else
      render 'new'
    end
  end

  private
  def list_params
    params.require(:list).permit(:name, :description, :private)
  end
end

这只是控制器的片段。

如果你能指出我正确的方向,我将不胜感激。

1 个答案:

答案 0 :(得分:2)

您可以将List模型修改为以下内容:

list.rb

class List < ApplicationRecord
  after_create :set_position
  .... existing model code ...

  private
  def set_position
    self.update_attribute(:position, self.id)
  end
end