has_many belongs_to relationship not passing through params - ruby-on-rails

I am making a small store admin
Product.rb
class Product < ActiveRecord::Base
has_many :product_options
accepts_nested_attributes_for :product_options
end
ProductOption.rb
class ProductOption < ActiveRecord::Base
belongs_to :product
end
products_controller.rb
class Admin::ProductsController < AdminApplicationController
def index
#products = Product.all
end
def new
#product = Product.new
end
def create
#product = Product.new(product_params)
if #product.save
redirect_to admin_products_path
end
#product_option = #product.product_options.create(params[:product_option])
end
def edit
#product = Product.find(params[:id])
end
def update
#product = Product.find(params[:id])
if #product.update(product_params)
redirect_to admin_products_path
end
end
def destroy
#product = Product.find(params[:id])
#product.destroy
flash[:notice] = "#{#product.name} has been deleted."
redirect_to admin_products_path
end
def upload
uploaded_io = params[:id]
File.open(Rails.root.join('public', 'product_pics', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
end
private
def product_params
params.require(:product).permit(:name, :product_id, :position, :product_description, :product_image_type, :product_image, :product_detail, :product_option_id, :option_name, :product_option )
end
end
product_option_controller.rb
class Admin::ProductOptionsController < AdminApplicationController
def index
#product_options = ProductOption.all
end
def new
#product_option = ProductOption.new
end
def create
#product_option = ProductOption.new(product_option_params)
end
def show
#product_option = ProductOption.find(params[:id])
end
end
private
def product_option_params
params.require(:product_option).permit(:option_name, :ranking, :total_redeemed, :product_id)
end
end
_form.html.erb
<%= simple_form_for([:admin, #product] , :html => {:multipart => true}) do |f| %>
<section class="main_content-header">
<div class="main_content-header-wrapper">
<nav class="main_content-breadcrumbs">
<ul class="breadcrumbs">
<li><%= link_to "All Products", admin_products_path %></li>
<h1> Edit Product </h1>
</ul>
</nav>
<div class="main_content-header-save">
<%= link_to "Cancel", admin_products_path, id: "main_content-header-save-cancel" %>
<%= f.submit %>
</div>
</div>
</section>
<div class="main_content-section">
<section class="main_content-section">
<div class="main_content-section-area">
<%= f.input :name %>
<%= f.input :product_description %>
<%= f.input :product_detail %>
<%= f.file_field :product_image %>
<p> If this product has options, enter them below</p>
<%= f.simple_fields_for :product_option, #product_option do |option_form| %>
<%= option_form.input :option_name %>
<% end %>
</div>
</section>
</div>
<% end %>
server output: ... keeps saying that :product_option is not permitted
Started POST "/admin/products" for 127.0.0.1 at 2014-10-15 16:13:25 -0700
Processing by Admin::ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"t96EMVlDND42HuVUzxWuss2bYDVhBokieTqN2Gz3N9I=", "commit"=>"Create Product", "product"=>{"name"=>"cvncvbn", "product_description"=>"cvbn", "product_detail"=>"", "product_option"=>{"option_name"=>"cvnbnvcb"}}}
Unpermitted parameters: product_option
SQL (1.5ms) BEGIN
SQL (0.4ms) INSERT INTO `products` (`created_at`, `name`, `product_description`, `product_detail`, `updated_at`) VALUES (?, ?, ?, ?, ?) [["created_at", "2014-10-15 23:13:25"], ["name", "cvncvbn"], ["product_description", "cvbn"], ["product_detail", ""], ["updated_at", "2014-10-15 23:13:25"]]
(0.4ms) COMMIT
Redirected to http://localhost:3000/admin/products
SQL (0.1ms) BEGIN
SQL (0.2ms) INSERT INTO `product_options` (`product_id`) VALUES (?) [["product_id", 119]]
(0.3ms) COMMIT
Completed 302 Found in 10ms (ActiveRecord: 2.8ms)
Started GET "/admin/products" for 127.0.0.1 at 2014-10-15 16:13:25 -0700
Processing by Admin::ProductsController#index as HTML
Product Load (0.3ms) SELECT `products`.* FROM `products`
Rendered admin/products/index.html.erb within layouts/admin (11.7ms)
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 7 ORDER BY `users`.`id` ASC LIMIT 1
Rendered admin/_header.html.erb (1.4ms)
Rendered admin/_nav.html.erb (0.4ms)
Completed 200 OK in 21ms (Views: 19.8ms | ActiveRecord: 0.6ms)
The record gets saved, so in the products options table there is just the product_id, .. but no other params....have tried a million things over the past 6 hours... so i dont really have a list of all the possible options, .. but if someone can see a glaring mistake your wisdom would be greatly appreciated.
--------------------------------------------------------------------------------------------
I figured it out, i was not using accepts_nested_attributes correctly these are the changes I had to get it all work.
-deleted the product_options controller (it was not needed)
-changed the product_params:
private
def product_params
params.require(:product).permit(:name, :product_id, :position, :product_description, :product_image_type, :product_image, :product_detail, :product_option_id,
:product_options_attributes => [:id, :option_name, :ranking, :total_redeemed, :product_id])
end
end
-deleted this line from the create action of the products controller
#product_option = #product.product_options.create(params[:product_option])
-added this line to the new action of the products controller
#product.product_options.build
-added an s to the ":product_option" in this loop (and deleted the '#product_option")
<%= f.simple_fields_for :product_option, #product_option do |option_form| %>
<%= option_form.input :option_name %>
<% end %>
the main change was adding the S... without it nested attributes was not being called at all

Try something like
def product_params
params.require(:product).permit(:name, :product_id, :position, :product_description, :product_image_type, :product_image, :product_detail, :product_option_id, :option_name, product_option: [:option_name] )
end

Related

Rails Nested Attributes with has_many through association not creating

I am trying to provide a way to generate a new object ("List") in one model with a new associated object in another ("Item") using a has_many through relationship (through "Groupings"). I was able to get the form working fine but can't figure out what I'm missing in order to finish the creation process correctly.
Rails v. 5.1.2, Ruby v. 2.4.1
lists_controller.rb
def new
#list = current_user.lists.new
3.times { #list.items.build }
end
def create
#list = current_user.lists.new(list_params)
respond_to do |format|
if #list.save
format.html { redirect_to #list, notice: 'List was successfully created.' }
format.json { render :show, status: :created, location: #list }
else
format.html { render :new }
format.json { render json: #list.errors, status: :unprocessable_entity }
end
end
end
private
def set_list
#list = List.find(params[:id])
end
def correct_user
#list = current_user.lists.find_by(id: params[:id])
redirect_to lists_path, notice: "Not authorized to edit this list"
if #list.nil?
end
def list_params
params.require(:list).permit(:title, {
item_attributes: [
:id, :title, :url
]})
end
items_controller.rb
def new
#item = Item.new
end
private
def set_item
#item = Item.find(params[:id])
end
def item_params
params.require(:item).permit(:title, :body, :url, :created,
:list_ids => [])
end
end
list.rb model
has_many :groupings, :dependent => :destroy
has_many :items, :through => :groupings
accepts_nested_attributes_for :items,
reject_if: ->(attrs) { attrs['title'].blank? || attrs['url'].blank? }
item.rb model
has_many :groupings, :dependent => :destroy
has_many :lists, :through => :groupings
validate :has_lists?
accepts_nested_attributes_for :lists
attr_writer :list_titles
after_save :assign_lists
def list_titles
#list_titles || lists.map(&:title).join(' ')
end
private
def assign_lists
if #list_titles
self.lists = #list_titles.split(/\,/).map do |title|
if title[0..0]==" "
title=title.strip
end
title=title.downcase
List.find_or_create_by_title(title)
end
end
end
def has_lists?
errors.add(:base, 'This item needs to be assigned to a list before it can be saved.') if self.lists.blank?
end
grouping.rb model
belongs_to :item
belongs_to :list
accepts_nested_attributes_for :item, :list
Lists Form
<%= form_with(model: list, local: true) do |f| %>
<% if list.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(list.errors.count, "error") %> prohibited this list from being saved:</h2>
<ul>
<% list.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title, id: :list_title %>
</div>
<div>
<p><strong>Items:</strong></p>
<%= f.fields_for :items do |item| %>
<div>
<%= item.label :title %>
<%= item.text_field :title %>
<%= item.label :url %>
<%= item.text_field :url %>
</div>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Sample Console Output
Started POST "/lists" for 127.0.0.1 at 2017-09-19 13:12:53 -0700
Processing by ListsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Y6rszWVUXDIVymuoBkXwvkw1pVbyC6mffiWIZzr7PVd1NT9JJi6rD72k5Fh2qU5Q5tEd0qn6bFYMSJnz2TgjAA==", "list"=>{"title"=>"Websites", "items_attributes"=>{"0"=>{"title"=>"Google", "url"=>"www.google.com"}, "1"=>{"title"=>"Yahoo", "url"=>"www.yahoo.com"}, "2"=>{"title"=>"Bing", "url"=>"www.bing.com"}}}, "commit"=>"Create List"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 2], ["LIMIT", 1]]
Unpermitted parameter: :items_attributes
(0.1ms) BEGIN
SQL (0.9ms) INSERT INTO "lists" ("title", "created_at", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["title", "Websites"], ["created_at", "2017-09-19 20:12:53.458577"], ["updated_at", "2017-09-19 20:12:53.458577"], ["user_id", 2]]
(0.3ms) COMMIT
Redirected to http://localhost:3000/lists/24
Completed 302 Found in 7ms (ActiveRecord: 1.6ms)
I'm still learning, clearly - but after trying all kinds of related hints on this forum I couldn't figure this one out. Thanks for any help!
You're almost there but there is an error being reported in your console logs: Unpermitted parameter: :items_attributes.
Change item_attributes to items_attributes in your list_params:
def list_params
params.require(:list)
.permit(:title, items_attributes: [:id, :title, :url])
end
You have some mistakes in your syntax when you define your params. It should be like this: (items instead item and you don't need {})
def list_params
params.require(:list).permit(:title,
items_attributes: [:id, :title, :url])
end

Cannot create answer through word by using accepts_nested_attributes_for

I am newbie on RoR. I try to create answer through word controller by using accepts_nested_attributes_for but when I click submit button, I get nothing and button got disable.
Here is my code.
word.rb
class Word < ApplicationRecord
belongs_to :category
belongs_to :exam
has_many :answers, dependent: :destroy
accepts_nested_attributes_for :answers
has_many :exam_words, dependent: :destroy
scope :alphabet, ->{order :content}
end
answer.rb
class Answer < ApplicationRecord
belongs_to :wordscope :alphabel, ->{order "content"}
validates :content, presence: true
end
new.html.erb
<% provide(:title, "Create word" )%>
<h1></h1>
<%= form_for #word do |f| %>
<%= f.label :word_content %>
<%= f.text_field :content, class: "form-control" %>
<%= f.fields_for :answers do |answer| %>
<%= answer.label :answer_content %>
<%= answer.text_area :content, class: "form-control" %>
<%= answer.label :is_correct %>
<%= answer.check_box :is_correct %>
<%end%>
<%= f.submit "create", class: "btn btn-primary"%>
<%end%>
words_controller.rb
class WordsController < ApplicationController
before_action :load_category, except: [:show, :new]
def index
#words = #category.words.includes(:answers).paginate(page: params[:page])
end
def new
#word = Word.new
#word.answers.new
end
def show
#word = Word.find_by_id(params[:id])
session[:w_id] = #word.id
end
def create
#word = #category.words.new(word_params)
#word.category_id = session[:cat_id]
#word.exam_id = 1
if #word.save
redirect_to category_path(session[:cat_id])
end
end
def destroy
#word = Word.find(params[:id])
if #word.present?
#word.destroy
end
redirect_to :back
end
def edit
#word = Word.find(params[:id])
end
def update
#word = Word.find(params[:id])
if #word.update_attributes(word_params)
flash[:success] = "Updated"
redirect_to category_path(session[:cat_id])
else
render 'edit'
end
end
private
def word_params
params.require(:word).permit :content,
answers_attributes: [:id, :content, :is_correct]
end
def load_category
#category = Category.find_by id: session[:cat_id]
unless #category
flash[:danger] = t "category_not_found"
redirect_to categories_path
end
end
end
This is what i get in server in terminal
Started POST "/words" for 127.0.0.1 at 2016-11-29 14:52:26 +0000
Processing by WordsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"qr4qCFAh6omymmgJK7aOjZO0HFtkyT3uwB0KGl6EL60MOipdCFgS0l+XwEi7adhPt1uF1TL2RdRGwsK79FX3iw==", "word"=>{"content"=>"new", "answers_attributes"=>{"0"=>{"content"=>"moi", "is_correct"=>"1"}}}, "commit"=>"create"}
Category Load (0.9ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.2ms) begin transaction
Exam Load (0.3ms) SELECT "exams".* FROM "exams" WHERE "exams"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.4ms) rollback transaction
No template found for WordsController#create, rendering head :no_content
Completed 204 No Content in 48ms (ActiveRecord: 2.7ms)
This is what show in my local web
==============SOLVED========================
I just find out how to solve, I forgot optional: true in answer.rd.
class Answer < ApplicationRecord
belongs_to :word, optional: true
scope :alphabel, ->{order "content"}
validates :content, presence: true
end

Ruby on Rails - Adding comments to post

Trying to learn RoR. Currently adding comments to posts by user. So far I have a posts model, comments model and post_comments model (to associate the two). So for in 'rails console' I can run: (say I set p = Post.first and c = Comment.first)
p.comments << c
This forms an association so it works in the console. I just can't seem to get the comments to form this association from the UI. So far I am creating the comments at "comments/new" (not sure if this is the issue. Do they need to be created on the "show view" for "post").
Here are some code snippets
Controllers
comments_controller.rb
class CommentsController < ApplicationController
def index
#comment = Comment.all
end
def new
#comment = Comment.new
end
def create
#comment = Comment.new(commentParams)
if #comment.save
flash[:success] = "Comment successfully added"
redirect_to comments_path(#comment)
else
render 'new'
end
end
def show
#comment = Comment.find(params[:id])
end
private
def commentParams
params.require(:comment).permit(:comment)
end
end
posts_controller
class PostsController < ApplicationController
before_action :setPost, only: [:edit, :update, :show, :destroy, :sold]
before_action :requireUser, except: [:index, :show]
before_action :requireSameUser, only: [:edit, :update, :destroy, :sold]
def index
#posts = Post.paginate(page: params[:page], per_page: 20)
end
def new
#post = Post.new
end
def create
#post = Post.new(postParams)
#post.user = currentUser
if #post.save
flash[:success] = "Post successfully added."
redirect_to post_path(#post)
else
render 'new'
end
end
def update
if #post.update(postParams)
flash[:success] = "Post successfully updated."
redirect_to post_path(#post)
else
render 'edit'
end
end
def show
end
def edit
end
def sold
#post.toggle(:sold)
#post.save
redirect_to post_path(#post)
end
def destroy
#post.destroy
flash[:danger] = "Item successfully deleted."
redirect_to posts_path
end
private
def postParams
params.require(:post).permit(:title, :price, :description, category_ids:[])
end
def setPost
#post = Post.find(params[:id])
end
def requireSameUser
if currentUser != #post.user and !currentUser.admin
flash[:danger] = "You can only edit or delete your own items"
redirect_to root_path
end
end
end
Models
comment.rb
class Comment < ActiveRecord::Base
belongs_to :post_comments
belongs_to :user
belongs_to :post
end
post_comment.rb
class PostComment < ActiveRecord::Base
belongs_to :post
belongs_to :comment
end
post.rb
class Post < ActiveRecord::Base
belongs_to :user
has_many :post_categories
has_many :categories, through: :post_categories
has_many :post_comments
has_many :comments, through: :post_comments
validates :title, presence: true,
length: { minimum: 4, maximum: 20 }
validates :description, presence: true,
length: { maximum: 1000 }
validates :user_id, presence: true
end
Views
posts/show.html.erb
<p>Comments: <%= render #post.comments %></p>
This renders the partial below
comments/_comment.html.erb
<%= link_to comment.name, comment_path(comment) %>
Finally is the new comment page as it is.
comments/new.html.erb
<h1>New Comment</h1>
<%= render 'shared/errors', obj: #comment %>
<div class="row">
<div class="col-xs-12">
<%= form_for(#comment, :html => {class: "form-horizontal", role: "form"}) do |f| %>
<div class="form-group">
<div class="control-label col-sm-2">
<%= f.label :comment %>
</div>
<div class="col-sm-8">
<%= f.text_area :comment, rows: 3, class: "form-control", placeholder: "Please enter a comment", autofocus: true %>
</div>
</div>
<div class="form-group">
<div class="center col-sm-offset-1 col-sm-10">
<%= f.submit class: "btn btn-primary btn-lg" %>
</div>
</div>
<% end %>
Any help would be greatly received.
Update
Log
Started GET "/posts/2" for ::1 at 2016-01-15 12:39:55 +0000
Processing by PostsController#show as HTML
Parameters: {"id"=>"2"}
[1m[36mPost Load (0.1ms)[0m [1mSELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1[0m [["id", 2]]
[1m[35mUser Load (0.1ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
[1m[36m (0.1ms)[0m [1mSELECT COUNT(*) FROM "posts" WHERE "posts"."user_id" = ?[0m [["user_id", 1]]
[1m[35mCategory Exists (0.1ms)[0m SELECT 1 AS one FROM "categories" INNER JOIN "post_categories" ON "categories"."id" = "post_categories"."category_id" WHERE "post_categories"."post_id" = ? LIMIT 1 [["post_id", 2]]
[1m[36mCategory Load (0.0ms)[0m [1mSELECT "categories".* FROM "categories" INNER JOIN "post_categories" ON "categories"."id" = "post_categories"."category_id" WHERE "post_categories"."post_id" = ?[0m [["post_id", 2]]
Rendered categories/_category.html.erb (0.2ms)
[1m[35mComment Load (0.1ms)[0m SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ? [["post_id", 2]]
Rendered comments/_comment.html.erb (0.1ms)
Rendered posts/show.html.erb within layouts/application (6.5ms)
[1m[36mCategory Load (0.1ms)[0m [1mSELECT "categories".* FROM "categories"[0m
Rendered layouts/_navigation.html.erb (0.9ms)
Rendered layouts/_messages.html.erb (0.1ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 52ms (Views: 50.3ms | ActiveRecord: 0.5ms)
As a comment can belong to a single post only, you do not need an association table (post_comments). You just need a simple one-to-many relationship.
Your post comment would be:
class Post < ActiveRecord::Base
has_many :comments
...
end
And comment would be like this:
class Comment < ActiveRecord::Base
belongs_to :post
...
end
Just make sure that you have the necessary post_id column in the comments table (you can check the db/schema.rb file). If that is missing, you can use the following migration to add it:
class AddPostIdToComments < ActiveRecord::Migration
def change
add_column :comments, :post_id, :integer
add_index :comments, :post_id
end
end
You also need to make sure you keep somewhere the reference to the post, whenever a user tries to create a comment to a post. You can add this in a hidden field to your comments/new.html.erb template. You could set the hidden field in the new action, in PostsController, after passing it through the URL.
So, in your posts/show.html.erb template you would have:
<%= link_to "Add Comment", new_comment_path(post_id: #post.id) %>
In your new action, in PostsController:
def new
#comment = Comment.new(post_id: params[:post_id])
end
And finally the hidden field in your form would be:
<%= f.hidden_field :post_id %>
Finally, add the post_id parameter to the list of permitted parameters in CommentsController.
instead of
In your new action, in PostsController:
def new
#comment = Comment.new(post_id: params[:post_id])
end
you can use this in the form views
<%= form.hidden_field :post_id, value: "#{params[:post_id]}" %>

Rails form_for edit not saving changes

I'm new to rails and having trouble getting my edit form to update attributes.
Here is my routes.rb for project and note:
resources :projects do
resources :notes
end
And this is my form_for in views/notes/edit.html.erb:
<%= form_for [#project, #note] do |f| %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :body %>
<%= f.text_area :body, rows: 10, class: "form-control" %>
</div>
<div class="action">
<%= f.submit "Save Note", class: "btn btn-success" %>
</div>
<% end %>
And finally this is my notes_controller.rb:
class NotesController < ApplicationController
before_action :find_note, only: [:show, :edit, :update, :destroy]
def index
#notes = Note.all
end
def new
#project = Project.find(params[:project_id])
#note = #project.notes.new
end
def create
#project = Project.find(params[:project_id])
#note = #project.notes.build(note_params)
#note.project = #project
#note.save ? flash[:notice] = "Note created." : flash[:error] = "Note could not be created, please try again."
redirect_to [current_user, #project]
end
def show
end
def edit
end
def update
if #note.update_attributes(note_params)
#note.save
flash[:notice] = "Note updated."
redirect_to authenticated_root_path
else
flash[:error] = "Could not update note."
render :edit
end
end
def destroy
#note.delete ? flash[:notice] = "Note deleted." : flash[:error] = "Note could not be deleted."
redirect_to user_project_path
end
private
def note_params
params.require(:note).permit(:title, :body)
end
def find_note
#project = Project.find(params[:project_id])
#note = #project.notes.find(params[:id])
end
end
This is what my terminal is outputting:
Started GET "/projects/12/notes/13/edit?utf8=%E2%9C%93&_method=patch&authenticity_token=vnIoOSi0ksMNI7uU0aMnBpkTBWi75wy%2BYvbs3RxO5sPIbvFzDA30%2B32dJxurdcsiu9zsIpuDCR%2FARUamBRrYmg%3D%3D&note%5Btitle%5D=Transporter+Materials&note%5Bbody%5D=Star+dust%2C+data&commit=Save+Note" for 127.0.0.1 at 2015-05-25 08:38:16 -0700
Processing by NotesController#edit as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"vnIoOSi0ksMNI7uU0aMnBpkTBWi75wy+Yvbs3RxO5sPIbvFzDA30+32dJxurdcsiu9zsIpuDCR/ARUamBRrYmg==", "note"=>{"title"=>"Transporter Materials", "body"=>"Star dust, data"}, "commit"=>"Save Note", "project_id"=>"12", "id"=>"13"}
Project Load (0.2ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? LIMIT 1 [["id", 12]]
Note Load (0.2ms) SELECT "notes".* FROM "notes" WHERE "notes"."project_id" = ? AND "notes"."id" = ? LIMIT 1 [["project_id", 12], ["id", 13]]
Rendered notes/edit.html.erb within layouts/application (3.4ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Completed 200 OK in 328ms (Views: 296.4ms | ActiveRecord: 2.3ms)
Thanks in advance for any suggestions.
If you are using #project.notes.build(note_params).
No need of this #note.project = #project in create action
and in update
if you are using #note.update_attributes(note_params)
this is not required #note.save
and its better try to debug it using #note.update_attributes!(note_params)
it will give you why its not able to save.
<%= form_for [#project, #note], :url => project_note_path(#project,#note), :method => :put do |f| %>

form_for submitting as PostsController#show instead of create when creating comments(nested)

I'm trying to figure out why my form is submitting wrong. I'm trying to implement nested comments under posts and my form renders but submits to the wrong action. I've tried a few things but cannot get it to work. I can create a comment via the rails console but not through my form. I was going through a railscast where he uses a older version of rails. I figured the main difference would be strong parameters but it doesn't seem to be working and I can't figure out what I'm missing here. Thanks.
This is my log
Started GET "/posts/1?utf8=%E2%9C%93&authenticity_token=PJmmRV6hnY%2Bgm4cVe5LSdALHezbI3ehMkud0yYTaA%2FQ%3D&comment%5Bname%5D=Mark&comment%5Bemail%5D=hustada80%40gmail.com&comment%5Bcontent%5D=this+is+a+comment&commit=Create+Comment" for 127.0.0.1 at 2014-10-08 14:34:53 -0500
Processing by PostsController#show as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"PJmmRV6hnY+gm4cVe5LSdALHezbI3ehMkud0yYTaA/Q=", "comment"=>{"name"=>"Mark", "email"=>"hustada80#gmail.com", "content"=>"this is a comment"}, "commit"=>"Create Comment", "id"=>"1"}
Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", 1]]
Rendered comments/_form.html.erb (4.2ms)
Rendered comments/_comments.html.erb (0.1ms)
Rendered posts/show.html.erb within layouts/application (53.1ms)
Rendered layouts/_header.html.erb (0.5ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 524ms (Views: 519.7ms | ActiveRecord: 0.2ms)
Here is my form ( a partial _form)
<div class="well">
<h4>Leave a comment</h4>
<form role="form" class="clearfix">
<%= form_for([#commentable, #comment]) do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.text_field :email, class: 'form-control', required: true %>
</div>
<div class="form-group">
<%= f.label :content %>
<%= f.text_area :content, class: 'form-control', required: true %>
</div>
<%= f.submit class: 'btn btn-primary' %>
<% end %>
</div>
Posts controller
class PostsController < ApplicationController
def new
#post = Post.new
end
def show
#post = Post.find(params[:id])
#commentable = #post
#comments = #commentable.comments
#comment = Comment.new
end
def index
#post = Post.all
#posts = Post.order('created_at DESC')
###posts_by_month = Post.find(:all, :order => 'created_at DESC').group_by { |post| post.created_at.strftime("%B %Y") }
end
def month_count
#posts_by_month = Post.find(:all, :order => 'created_at DESC').group_by { |post| post.created_at.strftime("%B %Y") }
end
def create
#post = Post.new(post_params)
#post.save
redirect_to #post
end
private
def post_params
params.require(:post).permit(:title, :text)
end
Comments Controller
class CommentsController < ApplicationController
before_action :load_commentable
def index
#comments = #commentable.comments
end
def new
#comment = #commentable.comments.new
end
def create
#comment = #commentable.comments.new(comments_params)
if #comment.save
redirect_to #commentable, notice: "Comment created."
else
render :new
end
end
def destroy
end
private
# def load_commentable
# resource, id = request.path.split('/')[1, 2]
# #commentable = resource.singularize.classify.constantize.find(id)
# end
def load_commentable
klass = [Post].detect { |c| params["#{c.name.underscore}_id"]}
#commentable = klass.find(params["#{klass.name.underscore}_id"])
end
def comments_params
params.require(:comment).permit(:content, :email, :name)
end
end
routes
Rails.application.routes.draw do
root 'posts#index'
get "sign_up" => "users#new", :as => "sign_up"
get "/log-in" => "sessions#new"
post "/log-in" => "sessions#create"
get "/log-out" => "sessions#destroy", as: :log_out
resources :posts do
resources :comments
end
resources :users
resources :sessions
Try something like
<%= form_for([#commentable, #comment], url: post_comments_path, method: :post) do |f| %>

Resources