0
0

More than 3 years have passed since last update.

【Rails】Ruby On Rails でデータベースを紐付ける手順

Last updated at Posted at 2020-09-30

モデルの設定

サンプルは1対多数

1側

post.rb
class Post < ApplicationRecord
  has_many :comments
end

多側

comment.rb
class Post < ApplicationRecord
  belongs_to :post
end

ルーティングの設定

routes.rb
resources :posts do
  resources :comments
end

※createとdestroyのみ使用する場合、下記の記述で他のルーティングにアクセス制限をかけることができる。

routes.rb
resources :posts do
  resources :comments, only: [:create, :destroy]
end

フォームでのパラメーターの受け取り方

[ ]で囲う。

???.html.rb
<%= form_for [@post, @post.comments.build] do |f| %>
<p>
  <%= f.text_field :body %>
</p>
<p>
  <%= f.submit %>
</p>
<% end %>

Destroyでの出し方、受け取り方

ルーティングから、postsは:post_id、commentsは:idでパラメーターを受け取ることができる。

DELETE /posts/:post_id/comments/:id(.:format)      comments#destroy
???.html.rb
<% if @post.comments.any? %>
<ul>
<% @post.comments.each do |comment|%>
<li><%= comment.body %><span> </span><span><%= link_to "[X]", post_comment_path(@post, comment), method: :delete %></span></li>
???.controller.rb
def destroy
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
  @comment.destroy
  redirect_to post_path(@post)
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0