【发布时间】:2014-01-13 04:04:34
【问题描述】:
我在这里使用 ruby on rails 指南 http://guides.rubyonrails.org/getting_started.html
在第 5.13 节中: 我在提交按钮上显示了两个不同的文本值,但在“_form”部分文件中,代码完全相同。 Rails 似乎会以某种方式自动更改文本值。在两个视图中发生这种情况的代码在哪里:new.html.erb 和 edit.html.erb。
(我的问题是手动控制文本,而是我试图了解 Rails 中这种自动行为的来源。)
_部分
<%= form_for @post do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited
this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
posts_controller
class PostsController < ApplicationController
def new
@posts = Post.all
@post = Post.new
end
def show
@post = Post.find(params[:id])
end
def index
@posts = Post.all
end
# called by the posts_path function
def create
@post = Post.new(post_params)
if @post.save
# Using redirect_to creates a new request.
redirect_to @post
else
# Using render sends back the @post variable's data!
# i.e. uses same request.
render 'new'
end
end
# Can only have one instance of render of redirect_to.
#render text: params[:post].inspect
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :text))
redirect_to @post
else
render 'edit'
end
end
def edit
@post = Post.find(params[:id])
end
# For SQL injection prevention.
private
def post_params
params.require(:post).permit(:title, :text)
end
结束
new.html.erb
新帖子
<%= form_for :post, url: posts_path do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited
this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= form_for :post do|f| %>
<% end %>
<%= link_to "List of Posts", posts_path %>
edit.html.erb
编辑帖子
<%= render 'form' %>
<%= link_to 'Back', posts_path %>
【问题讨论】:
-
我怀疑你还在外面,但对于未来的 Google 员工来说,指南中的这一部分非常有帮助:guides.rubyonrails.org/layouts_and_rendering.html 当我自己更好地理解它时,我会发布一个真实的答案而不是另一个RTM。 :D
-
该页面的哪个部分?
-
我从 2.1 节开始。我玩得越多,它对我的意义就越大。
标签: ruby-on-rails forms button submit