ruby - Sinatra and DataMapper Association -
i want make blog application in sinatra , datamapper, main application file this.
%w[rubygems sinatra data_mapper].each{ |r| require r } datamapper.setup(:default , env['database_url'] || "sqlite3://#{dir.pwd}/development.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 def admin? request.cookies[settings.username] == settings.token end def protected! halt [401, 'not authorized'] unless admin? end end post '/comment/create' 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 '/post/:id' @post = post.get(params[:id]) @comments = comment.new erb :post end delete '/comment/:id' post.get(params[:id]).comment.(params[:id]).destroy redirect '/post/'+post.id.to_s end datamapper.auto_upgrade!
now, problem how set instance variable of comments in post show file, make, delete, , show comments.
any suggestion , solutions welcomed.
if understand question, need. post.erb file like:
<h1><%= @post.title %></h1> <%= @post.body %> <% @post.comments.each |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, add post form right fields points /comments/create route.
the reason have form "delete" button in there because "delete '/comment/:id'" looking http delete method. unfortunately browsers don't implement that. looking "_method" field in post form how sinatra/rails/rack apps around that. then, near top of sinatra app, have tell "_method" field with:
use rack::methodoverride
hopefully that's asking.
Comments
Post a Comment