I want to make a blog application in Sinatra and DataMapper, my main application file is like this.
%w[rubygems sinatra data_mapper].each{ |r| require r }
DataMapper.setup(:default , ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/de开发者_如何学运维velopment.db")
class Post
include DataMapper::Resource
property :id, Serial
property :title, String
property :author, String
property :body, Text
has n, :comments
end
class Comment
include DataMapper::Resource
property :id, Serial
property :post_id, Serial
property :name, String
property :body, Text
belongs_to :post
end
helpers do
def admin?
request.cookies[settings.username] == settings.token
end
def protected!
halt [401, 'Not Authorized'] unless admin?
end
end
post '/comment/create' do
comment = Comment.new(:name => params[:name], :body => params[:body])
if comment.save
status 201
redirect '/post/'+post.id.to_s
else
status 412
redirect '/'
end
end
get '/post/:id' do
@post = Post.get(params[:id])
@comments = Comment.new
erb :post
end
delete '/comment/:id' do
Post.get(params[:id]).Comment.(params[:id]).destroy
redirect '/post/'+post.id.to_s
end
DataMapper.auto_upgrade!
Now, my problem is how to set up the instance variable of comments in the post show file, to make, delete, and show the comments.
Any suggestion and solutions would be welcomed.
If I understand your question, you already most everything you need. Your post.erb file could look something like:
<h1><%= @post.title %></h1>
<%= @post.body %>
<% @post.comments.each do |comment| %>
<p><%= comment.name %><br /><%= comment.body %></p>
<form action="/comment/<%= comment.id %>" method="post">
<input type="hidden" name="_method" value="delete" />
<input type="submit" value="Delete comment">
</form>
<% end %>
To create new comments, simply add a POST form with the right fields that points to your /comments/create route.
The reason I have that form with the "Delete" button in there is because your "delete '/comment/:id'" will be looking for the HTTP DELETE method. Unfortunately browsers don't actually implement that. Looking for a "_method" field in a POST form is how Sinatra/Rails/Rack apps get around that. Then, near the top of your Sinatra app, you have to tell it to look for that "_method" field with:
use Rack::MethodOverride
Hopefully that's what you were asking.
精彩评论