使用sinatra保存属于对象

时间:2016-08-08 13:18:25

标签: ruby database sinatra

我正在使用sinatra构建博客文章应用。每篇文章都会有很多评论。我可以创建Post,但comments并不想创建,我不知道为什么。

main.rb的

get "/" do
  @posts = Post.all
  haml :index
end

post '/new/post' do
  Post.create params['post']
  redirect to('/')
end 

post '/:id' do
  Post.get(params[:id]).comments.create(params['comment'])
  redirect to('/')
end

DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/development.db")

class Post
  include DataMapper::Resource
  property :id,              Serial
  property :title,           String
  property :content,         String
  property :photo,           String
  property :rating,          Integer
  has n, :comments, :constraint => :destroy

end

class Comment
  include DataMapper::Resource
  property :id,              Serial
  property :content,         String
  belongs_to :post

end
DataMapper.finalize

index.haml

 %form.new{:action => "/new/post", :method => "POST"}
  %input{:name => "post[title]", :type => "text"}/
  %input{:name => "post[content]", :type => "text"}/
  %input{:type => "submit", :value => "Publier"}/

%form.new{:action => "/#{post.id}", :method => "GET"}
  %input{:name => "_method", :type => "hidden", :method => "POST"} 
  %input{:content => "comment[content]", :type => "text"}/
  %input.button{:type => "submit", :value => "Commenter !"}

1 个答案:

答案 0 :(得分:1)

在您的表单中,方法是GET。但在你的应用程序中它是POST。

form.new{:action => "/#{post.id}", :method => "POST"}