Skip to content

Instantly share code, notes, and snippets.

@paulredmond
Created January 9, 2014 16:22
Show Gist options
  • Save paulredmond/8337018 to your computer and use it in GitHub Desktop.
Save paulredmond/8337018 to your computer and use it in GitHub Desktop.
Need help figuring out submitting a form for polymorphic models from associated controller
# models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
validates :name, presence: true
end
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new comment_params
@comment.status = 'pending'
respond_to do |format|
if @comment.save
format.html { redirect_to @post, notice: 'Comment was successfully created.' }
format.json { render action: 'show', status: :created, location: @comment }
else
format.html do
flash[:notice] = "Error creating comment: #{@comment.errors}"
redirect_to @post
end
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
end
# models/post.rb
class Post < ActiveRecord::Base
VALID_STATUSES = %w(draft published trash)
validates :status, inclusion: VALID_STATUSES
validates :title, :body, presence: true
has_many :comments, as: :commentable, dependent: :destroy
end
<%# posts/show.html.erb %>
<p id="notice"><%= notice %></p>
<p>
<strong>Title:</strong>
<%= @post.title %>
</p>
<p>
<strong>Body:</strong>
<%= @post.body %>
</p>
<p>
<strong>Status:</strong>
<%= @post.status %>
</p>
<hr />
<h2>Comments</h2>
<% @post.comments.each do |comment| %>
<div class="comment" style="border-bottom: 1px dotted grey">
<p>
<strong>Name:</strong>
<%= comment.name %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.comment %>
</p>
</div>
<% end %>
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :email %><br />
<%= f.text_field :email %>
</p>
<p>
<%= f.label :comment %><br />
<%= f.text_area :comment %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment