I am learning to use CRUD, and setup a page to add a record, however it only generated blank record? Can you take a look my code?
thanks!
here is the Page controller:
class PagesController < ApplicationController
def index
@test = Page.all
end
def new
@test = Page.new
end
def create
@test = Page.new(params.permit(:subject_id,:name,:position,:visible,:permalink))
if @test.save
flash[:notice] = "Page created successfully!"
redirect_to(:action => 'index')
else
render('new')
end
end
end
here is the new.html.erb
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>
<div class="pages new">
<h2>Create Subject</h2>
<%= form_for(:Page, :url => {:action => 'create'}) do |f| %>
<table summary="Page form fields">
<tr>
<th>Subject_ID</th>
<td><%= f.text_field(:subject_id) %></td>
</tr>
<tr>
<th>Name</th>
<td><%= f.text_field(:name) %></td>
</tr>
<tr>
<th>Position</th>
<td><%= f.text_field(:position) %></td>
</tr>
<tr>
<th>Visible</th>
<td><%= f.text_field(:visible) %></td>
</tr>
<tr>
<th>Permalink</th>
<td><%= f.text_field(:permalink) %></td>
</tr>
</table>
<div class="form-buttons">
<%= submit_tag("Create Subject") %>
</div>
<% end %>
</div>
Here is index.html.erb
<div class="pages index">
<h2>Pages</h2>
# <%= link_to("Add New Page", {:action => 'new'}, :class => 'action new') %>
<table class="listing" summary="Page list">
<tr class="header">
<th>Position</th>
<th>Page Name</th>
<th>Visible</th>
<th>Pages</th>
<th>Actions</th>
</tr>
<% @test.each do |f| %>
<tr>
<td><%= f.position %></td>
<td><%= f.name %></td>
<td class="center"><%= f.visible %></td>
<td class="center"><%= f.permalink %></td>
<td class="actions">
<%= link_to("Show", {:action => 'show', :id => f.id}, :class => 'action show') %>
<%= link_to("Edit", {:action => 'edit', :id => f.id}, :class => 'action edit') %>
<%= link_to("Delete", {:action => 'delete', :id => f.id}, :class => 'action delete') %>
</td>
</tr>
<% end %>
</table>
</div>
Thanks so much!
Strong parameters
Rails sends form parameters in nested hashes.
So to whitelist the parameters you would do.
which is like doing:
form_for and models
Also your form should read:
Or:
:Page
will give you the wrong key in your parameters and prevent rails from binding the form to your@page
object. (The values posted will disappear from the form when it's invalid).