【问题标题】:Nil foreign key in a nested form嵌套形式的 Nil 外键
【发布时间】:2010-05-10 17:24:37
【问题描述】:

我有一个包含以下模型的嵌套表单:

class Incident < ActiveRecord::Base
  has_many                :incident_notes 
  belongs_to              :customer
  belongs_to              :user
  has_one                 :incident_status

  accepts_nested_attributes_for :incident_notes, :allow_destroy => false
end

class IncidentNote < ActiveRecord::Base
  belongs_to :incident
  belongs_to :user
end

这是用于创建新事件的控制器。

def new
  @incident = Incident.new
    @users = @customer.users
    @statuses = IncidentStatus.find(:all)
    @incident.incident_notes.build(:user_id => current_user.id)

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @incident }
  end
end

def create
  @incident = @customer.incidents.build(params[:incident])
  @incident.incident_notes.build(:user_id => current_user.id)

  respond_to do |format|
    if @incident.save
      flash[:notice] = 'Incident was successfully created.'
      format.html { redirect_to(@incident) }
      format.xml  { render :xml => @incident, :status => :created, :location => @incident }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @incident.errors, :status => :unprocessable_entity }
    end
  end
end

这一切都以事件的嵌套形式存在。 event_notes 表单有一个文本区域,嵌套在事件中。

所以我的问题是,每当我创建事件时,incident_notes 条目都会提交两次。第一个插入语句使用来自文本区域的文本创建了一个incident_note 条目,但它没有将用户的user_id 作为外键附加。第二个条目不包含文本,但它有 user_id。

我想我可以这样做:

@incident.incident_notes.build(:user_id => current_user.id)

但这似乎并没有按我想要的方式工作。如何将 user_id 附加到 event_note?

谢谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我终于明白了。我需要在事件控制器中执行此操作:

    def create
      @incident = @customer.incidents.build(params[:incident])
      @incident.incident_notes.first.user = current_user
    

    而不是:

    def create
      @incident = @customer.incidents.build(params[:incident])
      @incident.incident_notes.build(:user_id => current_user.id)
    

    【讨论】:

      【解决方案2】:

      我认为你不需要

      @incident.incident_notes.build(:user_id => current_user.id)
      

      new 操作上。您正在构建 incident_notes 两次。

      【讨论】:

      • 如果我从新建中删除它,文本区域不会显示在视图中。但是,如果我从创建中删除它,它会修复重复。但是,我仍然无法在 IncidentNotes 表中设置 user_id 外键: IncidentNote Create (0.1ms) INSERT INTO "incident_notes" ("created_at", "updated_at", "user_id", "note", "incident_id") VALUES('2010-05-10 20:50:02', '2010-05-10 20:50:02', NULL, 'This is a note', 10) 我不知道如何将 user_id 设置为 current_user id。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多