Нулевой внешний ключ во вложенной форме - PullRequest
1 голос
/ 10 мая 2010

У меня есть вложенная форма со следующими моделями:

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

Все это существует во вложенной форме для инцидента. Для формы инцидентных примечаний есть текстовая область, вложенная в инцидент.

Так что моя проблема в том, что записьident_notes отправляется дважды, когда я создаю инцидент. Первый оператор вставки создает записьident_note с текстом из текстовой области, но он не присоединяет user_id пользователя в качестве внешнего ключа. Вторая запись не содержит текст, но имеет идентификатор пользователя.

Я думал, что смогу сделать это с:

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

но это не работает так, как я хочу. Как я могу прикрепить идентификатор пользователя к сообщению инцидента?

Спасибо!

Ответы [ 2 ]

2 голосов
/ 11 мая 2010

Я наконец понял это. Мне нужно было сделать это в контроллере инцидентов:

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)
1 голос
/ 11 мая 2010

Не думаю, что вам нужно

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

на new действииВы строите incident_notes дважды.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...