I'm using the ruby on rails guide here http://guides.rubyonrails.org/getting_started.html
In section 5.13: I am getting two different text values displayed on the submit button, but in the "_form" partial file, the code is exactly the same. Rails seems to automatically change the text values somehow. Where is the code that is making this happen in the two views: new.html.erb and edit.html.erb.
(My question to control the text manually, but rather, I'm trying to understand where this automatic behavior is coming from in Rails. )
_partial
<%= 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
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 %>
if you want to change text at form's submit button:
<%= f.submit ( f.object.new_record? ? "Create" : "Update"), class: "btn" %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With