Use a hidden field will fix my issue… i got it..
Hi All,
I am new to rails, trying to do some practice.
The app i am writing is trying to create a new “Post” See the view and controller below.
But it doesn`t work as what i expected…
the parameters pass to function “save”, there is no “post_at” field…
How can i fix it???
Thanks
INFO: Parameters: {"authenticity_token"=>"Xc9VuvRL6GsUTaKyyNQxp8ovylEYwOMC+7hMcqdKizg=", "post"=>{"title"=>"First post", "content"=>"Write something"}, "commit"=>"save"}
View new_post.erb
<div class="post">
<% form_for @new_post, :url => { :action => "save" } do |f| %>
<p><%= f.error_messages %></p>
<br/>
<table>
<tr>
<td>Title</td>
<td><%= f.text_field :title %></td>
</tr>
<tr>
<td>Post at</td>
<td><%= @new_post.post_at %></td>
</tr>
<tr>
<td>Message</td>
<td><%= f.text_area :content, :cols => 100, :rows => 10 %></td>
</tr>
</table>
<br/>
<%= f.submit 'save'%>
<% end %>
</div>
Post Controler
class PostController < ApplicationController
def index
@all_posts = Post.find(:all)
render :action => "post"
end
def new
@new_post = Post.new
@new_post.post_at = Time.now
render :action => "new_post"
end
def save
@new_post = params[:post]
Post.create(@new_post)
redirect_to "/post"
end
end
Data Model:
class Post
include DataMapper::Resource
storage_names[:default] = "Post"
property :id, Serial
timestamps :at
property :title, String, :required => true, :length => 500
property :content, Text, :required => true, :lazy => false
property :post_at, DateTime
end
First off, your development will be a lot easier if you follow the REST principles.
Your controller should instead of
saveimplement thecreateandupdatemethods.This is a complete REST controller which has the views
index.html.erb, new.html.erb, edit.html.erb, show.html.erball inapp/views/posts.Sidenote: If you’re new to Rails, it might be a good idea to learn how to use it with ActiveRecord before trying on DataMapper. That way you can use
rails generate scaffoldto get a full example of a way to do all this.