Question

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?

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top