0

基本上我在警报和更新之间有一对多的关系。许多更新属于一个警报。现在我的问题是我无法更新数据库中的任何记录。我可以毫无问题地创建新记录。Rails 记录器将实际记录打印到日志中。正如您从日志文件中看到的那样,@new_alert 检索更改的记录,该记录应保存到数据库中。虽然它说“警报已成功更新”,但它不会用新记录更新旧记录。当我删除警报和更新之间的关系时,它会完美运行。我想我错过了警报或更新模型中的某些内容。

alerts_controller.rb ...

def update
@alert = Alert.find(params[:id])
    @new_alert = params[:alert]

    Rails.logger.debug "alert_params: #{@new_alert.inspect}"
    Rails.logger.debug "alert_db: #{@alert.inspect}"


respond_to do |format|
  if @alert.update_attributes(params[:alert])
    format.html { redirect_to @alert, notice: 'Alert was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render action: "edit" }
    format.json { render json: @alert.errors, status: :unprocessable_entity }
  end
end 
end...

警报.rb

class Alert < ActiveRecord::Base
  has_many :update  
  accepts_nested_attributes_for :update
end

更新.rb

class Update < ActiveRecord::Base
belongs_to :alert, :foreign_key => 'alert_id'  
end

(MySQL) 警报表:

CREATE TABLE `alerts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status_id` int(11) DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `update_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)

(MySQL) 更新表:

CREATE TABLE `updates` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `alert_id` int(11) DEFAULT NULL,
  `text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)

日志输出:

Started PUT "/alerts/4" for 127.0.0.1 at 2012-08-24 15:47:12 +0200
Processing by AlertsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"GHM+S34PV4o46SpZZm67+mM8Lu9eY/BiWGMjDpwju9c=", "alert"=>{"title"=>"afgaegafga56556", "text"=>"afgafgafgarg", "status_id"=>"2"}, "commit"=>"Update Alert", "id"=>"4"}
  [1m[35mAlert Load (0.5ms)[0m  SELECT `alerts`.* FROM `alerts` WHERE `alerts`.`id` = 4 LIMIT 1
alert_params: {"title"=>"afgaegafga56556", "text"=>"afgafgafgarg", "status_id"=>"2"}
alert_db: #<Alert id: 4, status_id: 2, date: "2012-08-22 20:00:19", text: "afgafgafgarg", title: "afgaegafga", update_id: 1>
  [1m[36m (0.0ms)[0m  [1mBEGIN[0m
  [1m[35mUpdate Load (0.5ms)[0m  SELECT `updates`.* FROM `updates` WHERE `updates`.`alert_id` = 4
  [1m[36m (0.5ms)[0m  [1mCOMMIT[0m
Redirected to http://localhost:3000/alerts/4
Completed 302 Found in 4ms (ActiveRecord: 1.5ms)

谢谢!

4

1 回答 1

2

has_many :update应该是复数:has_many :updates否则关系可能不起作用。

对于accepts_nested_attributes_for.

此外(不重要但可能很高兴知道)当它与关系名称匹配时,您不必定义外键。所以belongs_to :alert, :foreign_key => 'alert_id'是完全一样的belongs_to :alert

于 2012-08-24T15:23:24.497 回答