我想根據@project.update
是否更改屬性來有條件地顯示/隱藏某個視圖中的某些元素。成功屬性更新後未將模型實例標記爲已更改
我想知道爲什麼我的模型實例在成功的屬性更新後未被標記爲已更改。
看來,ActiveModel::Dirty
不正確地表明我的模型的屬性已更改或更可能我沒有正確使用它。
這裏是一個註釋日誌PATCH
請求我對我的ProjectController#update
行動。在這裏你會看到屬性改變了,但模型實例沒有反映出來。對於它的價值,控制器是通過Rails腳手架操作生成的。沒有什麼特別的。
#
# FORM SUBMITTED FROM BROWSER WITH A CHANGE TO THE ATTRIBUTE NAMED "title"
#
Started PATCH "/projects/2" for 127.0.0.1 at 2016-04-23 15:47:38 -0700
Processing by ProjectsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"0JH/fEKx+Qk6mOY+eVTteKQUKrZUVXroKzMxuztrTzE/voI+PtzmQnJLGVM5bgdmzJyHDpAon3dzcvvjJ3yEtQ==", "project"=>{"title"=>"changed"}, "commit"=>"Update Project", "id"=>"2"}
Project Load (0.1ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
#
# DEBUGGER KICKS IN BEFORE THE UPDATE HAS HAPPENED
#
[40, 49] in app/controllers/projects_controller.rb
40:
41: # PATCH/PUT /projects/1
42: # PATCH/PUT /projects/1.json
43: def update
44: byebug
=> 45: respond_to do |format|
46: if @project.update(project_params)
47: format.html { redirect_to @project, notice: 'Project was successfully updated.' }
48: format.json { render :show, status: :ok, location: @project }
49: else
#
# PROJECT TITLE IS STILL UNMOLESTED
#
(byebug) @project
<Project id: 2, title: "ORIGINAL_TITLE", created_at: "2016-04-23 22:47:30", updated_at: "2016-04-23 22:47:30">
# PROVE PARAMS CONTAIN A CHANGED ATTRIBUTE
(byebug) project_params
<ActionController::Parameters {"title"=>"changed"} permitted: true>
#
# TRIGGER UPDATE AND PERSIST NEW TITLE
#
(byebug) @project.update(project_params)
(0.2ms) begin transaction
SQL (0.9ms) UPDATE "projects" SET "title" = ?, "updated_at" = ? WHERE "projects"."id" = ? [["title", "changed"], ["updated_at", 2016-04-23 22:48:13 UTC], ["id", 2]]
(3.5ms) commit transaction
true
#
# WAT?
#
(byebug) @project.changes
{}
(byebug) @project.changed?
false
(bye bug)
這裏是我的ProjectsController#update
行動(標準導軌支架):
# app/controllers/projects_controller.rb
# PATCH/PUT /projects/1
# PATCH/PUT /projects/1.json
def update
byebug
respond_to do |format|
if @project.update(project_params)
format.html { redirect_to @project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: @project }
else
format.html { render :edit }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
相應的視圖形式(也產生腳手架):
# app/views/projects/_form.html.erb
<%= form_for(project) do |f| %>
<% if project.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% project.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
你可以發佈你的'更新'方法和'窗體' – 7urkm3n
你能告訴我你到底在做什麼?是否就像你想在更新之後做一些事情,如果有任何改變? – Alfie
我添加了更多的信息來回答這兩個請求。 –