Userテーブル
Productテーブル
Commentテーブル
の3つのテーブルが存在し、以下のように構成しています。
models/user.rb
Ruby
1has_many :comments, dependent: :destroy
models/product.rb
Ruby
1has_many :comments, dependent: :destroy
models/comment.rb
Ruby
1belongs_to :user 2belongs_to :product
この時、コメントのレコードをどういった形で作るかについて分からないことがありました。
現在は、
controllers/products_controller.rb
Ruby
1def show 2 @product = Product.find(params[:id]) 3 @comment = current_user.comments.build 4end
views/products/show.html.erb
Ruby
1<%= form_for(@comment) do |f| %> 2 <%= f.hidden_field :product_id, value: @product.id %> 3 4 <div> 5 <%= f.text_area :comment %> 6 </div> 7 8 <div> 9 <%= f.submit "コメントする" %> 10 </div> 11<% end %>
といった感じで、 products/1
といったURLのパラメーターから product_id
を取ってきて隠しデータとして送信する形で上手くいっているのですが、
他に推奨されている方法はありますでしょうか?
もし知っている方がいらっしゃるようでしたら、教えて頂きたいです。
追加
Ruby
1create_table "comments", force: :cascade do |t| 2 t.integer "user_id" 3 t.integer "idea_id" 4 t.text "comment" 5 t.datetime "created_at", null: false 6 t.datetime "updated_at", null: false 7 t.index ["idea_id", "created_at"], name: "index_comments_on_idea_id_and_created_at" 8 t.index ["idea_id"], name: "index_comments_on_idea_id" 9 t.index ["user_id", "created_at"], name: "index_comments_on_user_id_and_created_at" 10 t.index ["user_id"], name: "index_comments_on_user_id" 11 end