In my Rails application, I have few models that:
I need to make belog comments either before Photo, or, Albumand obviously always belong User. I am going to use polymorphic associations for this.
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :commentable, :polymorphic => true
end
The question is, what is the Rails way of describing the action #createfor the new comment. I see two options.
1. Describe the creation of comments in each controller
But this is not a DRY decision. I can make one general partial view for displaying and creating comments, but I will have to repeat that I write comment logic for each controller. So it does not work.
2. Create a new comment. Controller
, , , ,
, , type ,
:
# schema.rb
create_table "comments", force: :cascade do |t|
t.text "body"
t.integer "user_id"
t.integer "commentable_id"
t.string "commentable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
, , :
class CommentsController < ApplicationController
def new
@comment = Comment.new
end
def create
@commentable = ???
if @comment.save(comment_params)
respond_to do |format|
format.js {render js: nil, status: :ok}
end
end
end
private
def comment_params
defaults = {:user_id => current_user.id,
:commentable_id => @commentable.id,
:commentable_type => @commentable.type}
params.require(:comment).permit(:body, :user_id, :commentable_id,
:commentable_type).merge(defaults)
end
end
commentable_id commetable_type? , commentable_type .
, form_for @comment ?