Alexander Munck Alexander Munck - 3 months ago 12
Ruby Question

Rendering comment form into other view except post view

I am trying to render my comment form into another view except the post view, but i am getting the error:
No route matches {:action=>"index", :controller=>"comments", :post_id=>nil} missing required keys: [:post_id]

My models:

class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
end

class Post < ApplicationRecord
belongs_to :user
has_many :comments
mount_uploader :image, AvatarUploader
validates :content, presence: true, length: {minimum: 5}
delegate :username, :username=, :email, :email=,:avatar, :avatar=, :to => :user, allow_nil: true

end


class Wall < ApplicationRecord
has_many :post
has_many :users
has_many :comments

delegate :username, :username=,:avatar, :avatar=, :email, :email=, :to => :user, allow_nil: true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end


And my form that i am rendering in the wallcontroller -> index.html.erb

<div class="comments">
<%= form_for ([@post, @post.comments.build]) do |f| %>
<%= f.text_area :content, class: 'comments js-auto-size', id: 'alex2' ,:rows => 1 %>
<%= f.submit "Submit", class: "btn btn-default" %>
<% end %>
</div>


UPDATE:

Rails.application.routes.draw do
devise_for :users
resources :uploads
resources :users
resources :walls
resources :posts do
resources :comments
end
root 'walls#index'
end


Adding this form to the post view works with no problem, however i wish to render both this form and comments into the wall index.html.erb

This app is basically like a facebook, so everything will be rendered on 1 page.

Answer

The wall index shows all posts (presumably) so you must have some construct like...

<% @posts.each do |post| %>
...

<% end %>

So between the do and the end you have a post object, so you can render the form without the instance variable, instead as...

<div class="comments">
<%= form_for ([post, post.comments.build]) do |f| %>
    <%= f.text_area :content, class: 'comments js-auto-size', id: 'alex2' ,:rows => 1  %>
    <%= f.submit "Submit", class: "btn btn-default" %>
  <% end %>
</div>