collection_select - Rails 4 的嵌套属性

Nested attributes with collection_select - Rails 4

当我按下提交按钮时,它会转到我的 'create' 操作,然后保存主 object,但外键为空,因为它尚未通过 [=29= 传递],这是我的代码:

型号:

class Ticket < ActiveRecord::Base
  belongs_to :system

  validates :title, presence: true, length: {minimum: 1, maximum: 60}

  accepts_nested_attributes_for :system
end

class System < ActiveRecord::Base
  has_many :tickets
  validates :name, presence: true, length: {minimum: 1, maximum: 50}
end

控制器:

class TicketsController < ApplicationController
  def new
    @system = System.actives
    @priority = Priority.actives
    @ticket = Ticket.new
    respond_to :js, :html
  end

  def create
    @ticket = Ticket.new(ticket_params)
    @ticket.save
    respond_with(@ticket)
  end

  def ticket_params
    params.require(:ticket).permit(:title, :active, systems_attributes: [:id,:name])
  end
end

查看

<%= form_for @ticket, remote: true do |f| %>

  <div class="form-group">
    <%= f.label :Título %><br>
    <%= f.text_field :title, class: 'form-control' %>
  </div>

  <div class="form-group">
    <%= f.label :Sistema %><br>
    <%= f.fields_for :systems do |fs| %>
    <%= fs.collection_select :id,
      @system.order(:name),:id,:name, {include_blank: 'Selecione...'},
      {class: 'form-control', id: 'system_select'}%>
    <% end %>
  </div>

  <div class="actions">
    <%= f.submit "Abrir Chamado", class: "btn btn-info" %>
  </div>

<% end %>

因此,它保存了带有标题的票 object,但没有 system_id,任何有用的提示都会在这里很好。

我不完全理解你的表格,但在 ticket_params 中,你似乎在 systems_attributes 的数组值中有你想要的 :id。如果这确实是您要传递的新 Ticket,那么它需要在 Ticket.new 中以不同的方式传递。您使用 ticket_params 传递给 Ticket.new 的 arguments/options 散列应该是键值对,如下所示:

Ticket.new(title: "yourtitle", other: "whatever", system_id: "your_id")

我要么更改 ticket_params 的输出,以便它以这种方式传递给您的 system_id,要么在您的 [=19] 中手动将其传入(将其从参数中键入) =] 动作。

您的代码中几乎没有错误。

首先,在您的 new 操作中,您需要添加这一行 @ticket.build_system

def new
  @system = System.actives
  @priority = Priority.actives
  @ticket = Ticket.new
  @ticket.build_system
  respond_to :js, :html
end

你的ticket_params方法应该是这样的

def ticket_params
  params.require(:ticket).permit(:title, :active, system_id,system_attributes: [:id,:name])
end

通知system_idsystem_attributes

最后,您需要将此行 <%= f.fields_for :systems do |fs| %> 更改为 <%= f.fields_for :system do |fs| %>