我刚开始学习rails。我正在尝试创建一个页面来显示评论/内容以及添加评论。 这就是我的更新控制器的样子:
def update_memo
@article = Article.find_by_id(params[:id])
@article.update_attributes(:memo => params[:remark])
redirect_to :back
end
这就是我的表格:
<%= form_for @article.memo, url: {action: "update_memo", id: @article.id}, html: {method: "put"} do |f| %>
<%= f.label :'Comment:' %>
<%= f.text_field :remark %>
<%= f.submit "Save !"%>
<% end %>
第一次更新备忘录字段时很好。但是当我再次尝试更新时。它显示“Mysql2 :: Error:Column'备忘录'不能为空”
Started PUT "/showarticle/update_memo?id=1"
Processing by ShowarticleController#update_memo as HTML
Parameters: {"utf8"=>"‚ì", "authenticity_token"=>"LXEUxk>wI9W+VpAP+mpULojiGeYTDoSBIjrCkkA3GacYwZLZyJyfHFOsoxwdSS5LUoQDuP3FGidopp2KA==", "test1"=>{"remark"=>"test0"}, "commit"=>"Save !", "id"=>"1"}
Article Load (1.8ms) SELECT `articles`.* FROM `articles` WHERE `articles`.`id` = 1 LIMIT 1
(1.5ms) BEGIN
SQL (3.5ms) UPDATE `articles` SET `memo` = NULL WHERE `articles`.`id` = 1
Mysql2::Error: Column 'memo' cannot be null: UPDATE `articles` SET `memo` = NULL WHERE `articles`.`id` = 1
(1.5ms) ROLLBACK
Completed 500 Internal Server Error in 14ms (ActiveRecord: 8.3ms)
答案 0 :(得分:0)
将文章对象传递给form_for帮助程序:
<%= form_for @article, url: {action: "update_memo", id: @article.id}, html: {method: "put"} do |f| %>
<%= f.label :'Comment:' %>
<%= f.text_field :memo %>
<%= f.submit "Save !"%>
<% end %>
你的控制者的行动:
def update_memo
@article = Article.find_by_id(params[:id])
@article.update_attributes(:memo => params][:article][:memo])
redirect_to :back
end
我建议你阅读一下strong_parameters(http://api.rubyonrails.org/classes/ActionController/Parameters.html)
答案 1 :(得分:0)
这样做:
#config/routes.rb
resources :articles do
resources :memos #-> url.com/articles/:article_id/memos/new
end
#app/controllers/memos_controller.rb
class MemosController < ApplicationController
def new
@article = Article.find params[:article_id]
@memo = @article.memos.new
end
def create
@article = Article.find params[:article_id]
@memo = @article.memos.new memo_params
@memo.save
end
private
def memo_params
params.require(:memo).permit(:article_id, :remark)
end
end
#app/views/memos/new.html.erb
<%= form_for @memo do |f| %>
<%= f.text_field :remark %>
<%= f.submit %>
<% end %>