0

I'm trying to implement comments for my posts in a Sinatra blog. This is my db for comments and posts:

DB.create_table :Posts do
primary_key :id
String :Title
String :Content
end

DB.create_table :Comments do 
primary_key :id
String :Content
foreign_key(:Post_id, :Posts)
end

This is the model:

class Post < Sequel::Model
one_to_many :Comments
end

class Comment < Sequel::Model
many_to_one :Posts
end

This is my erb:

<form action="/comments" method="post">
<div class="form-group">
<label for="Content">Comment:</label>
<br>
<textarea id="Content" class="form-control" name="Content" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>

This is my controller code:

post "/comments" do
@comment = Comment.insert(:Content => params[:Content], :Post_id => ???? )
end

I want to insert the id of the post that the specific comment was written into the :Post_id attribute/foreign key (where the question marks are).

I want this so I could later display each comment to the appropriate post.

Can you help me with this, and direct me to the right path please?

uklp
  • 551
  • 1
  • 6
  • 14

1 Answers1

0

Normally I'd insert the post ID in the form as a hidden field. Well, assuming you render the comment form on a post page

<form action="/comments" method="post">
  ...
  <input type="hidden" name="post_id" value="<%= @post.id %>" />
</form>

Then in your ruby you can just grab it from the params

@comment = Comment.insert(:Content => params[:Content], :Post_id => params[:post_id]

Btw, just a word of advise, you should use the down case, underscored style for your properties (I'm talking about Content and Post_id) coz it's kinda the Ruby way. Capitalized style is used for classes and downcase underscored for properties

Nikolay
  • 1,392
  • 1
  • 9
  • 15
  • Thank you man. Now it works perfectly. Can you also tell me, after I insert the comment, how can I redirect the view to that post again? Sorry for my style, I'm still a newbie at Ruby, I'm trying to improve on this too. – uklp Dec 11 '13 at 02:42
  • sure just say `redirect "/post/#{post_id}"` or something like that after you create a comment that should do the trick – Nikolay Dec 11 '13 at 02:46