我有一个奇怪的案例。我的同事和我都无法弄清楚为什么它不起作用。也许有人有类似的情况,或者可以发现我们忽略的任何东西。这是我们所拥有的:
Rails 3.2.6 mysql 数据库
我们有一个Comment
模型。像这样:
# == Schema Information
#
# Table name: comments
#
# id :integer not null, primary key
# username :string(255)
# realname :string(255)
# email :string(255)
# title :string(255)
# content :text
# comment_date :datetime
# article_id :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# rating :float
#
class Comment < ActiveRecord::Base
attr_accessible :username, :realname, :email, :title, :content, :comment_date, :article_id, :rating
belongs_to :article, class_name: Goldencobra::Article, foreign_key: "article_id"
end
我试过attr_accessible
有无效果。
我创建了一个CommentsController
这样的:
class CommentsController < ApplicationController
skip_before_filter :verify_authenticity_token
protect_from_forgery only: [:index]
def index
@article = Goldencobra::Article.find(params[:id])
@comments = @article.comments
respond_to do |format|
format.rss
end
end
def create
@comment = Comment.new(params[:comment])
@comment.save!
flash[:notice] = 'Comment was successfully created.'
rescue ActiveRecord::RecordInvalid
render :action => :new
end
def update
@comment = Comment.find(params[:id])
if @comment && @comment.update_attributes(params[:comment])
render text: "Success", layout: false
else
render text: "No success", layout: false
end
end
end
我想要的是使用更新操作来更新评论模型。就像我们每次做的一样。小菜一碟……只是,它不会更新。这是我测试更新的方法:
require 'spec_helper'
describe CommentsController do
def do_create
@article = Goldencobra::Article.create(title: "Testartikel", article_type: "Default Show")
post :create, :comment => {username: "johnny",
realname: "John Doe",
email: "johnny@gmail.com",
title: "Great title",
content: "What an awesome article.",
article_id: @article.id,
rating: 3.4}
end
it "should update a comment" do
do_create
put :update, id: Comment.first.id, comment: {title: "New great title"}
Comment.first.title.should eql("New great title")
end
end
我通过 REST 客户端(OS X 上的 Rested.app)更新尝试了同样的事情
我总是得到“成功”的回应。.update_attributes()
总是成功。问题是:它没有任何改变。这是来自 restful 尝试的控制台日志:
Started PUT "/comments/10" for 127.0.0.1 at 2012-07-18 12:35:13 +0200
Processing by CommentsController#update as HTML
Parameters: {"comment"=>{"title"=>"neuer test"}, "id"=>"10"}
Comment Load (0.4ms) SELECT `comments`.* FROM `comments` WHERE `comments`.`id` = 10 LIMIT 1
(0.1ms) BEGIN
(0.1ms) COMMIT
Rendered text template (0.0ms)
Completed 200 OK in 4ms (Views: 0.4ms | ActiveRecord: 0.6ms | Solr: 0.0ms)
这是它的样子,当我在 rails 控制台中尝试同样的薄时:
1.9.2p290 :017 > Comment.last.update_attributes(title: "test 2")
Comment Load (0.8ms) SELECT `comments`.* FROM `comments` ORDER BY `comments`.`id` DESC LIMIT 1
(0.2ms) BEGIN
(0.5ms) UPDATE `comments` SET `title` = 'test 2', `updated_at` = '2012-07-18 09:48:39' WHERE `comments`.`id` = 10
(3.4ms) COMMIT
=> true
缺少的是UPDATE
评论SET
标题= 'test 2',
updated_at= '2012-07-18 09:48:39' WHERE
评论.
id = 10
。谁能告诉我为什么我的控制器不更新模型?
谢谢你。