我试图渲染我的评论表单到另一个视图,除了post视图,但我得到的错误:没有路由匹配{:action=>"index",:controller=>"comments",:post_id=>nil}缺少必需的键:[:post_id]
我的模型:
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
我在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>
更新:Rails.application.routes.draw do
devise_for :users
resources :uploads
resources :users
resources :walls
resources :posts do
resources :comments
end
root 'walls#index'
end
将此表单添加到post视图中没有问题,但是我希望将此表单和评论都呈现到wall index.html.erb
这个应用程序基本上就像一个facebook,所以所有的东西都会在一个页面上呈现。
墙索引显示所有的帖子(大概),所以你必须有一些结构,如…
<% @posts.each do |post| %>
...
<% end %>
所以在do
和end
之间你有一个post
对象,所以你可以在没有实例变量的情况下渲染表单,而不是…
<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>