【问题标题】:Rendering comment form into other view except post view将评论表单渲染到除帖子视图之外的其他视图
【发布时间】:2017-01-09 20:17:41
【问题描述】:

我正在尝试将我的评论表单呈现到除帖子视图之外的另一个视图中,但我收到了错误: 没有路由匹配 {:action=>"index", :controller=>"cmets", :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

我在墙控制器中呈现的表单 -> 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

将此表单添加到帖子视图没有问题,但是我希望将此表单和 cmets 都呈现到墙上 index.html.erb

这个应用程序基本上就像一个 facebook,所以所有内容都将在 1 页上呈现。

【问题讨论】:

  • 你能显示你的 routes.rb 吗?
  • 添加路由到帖子

标签: ruby-on-rails ruby


【解决方案1】:

墙索引显示所有帖子(大概),所以你必须有一些结构,比如......

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

<% end %>

所以在doend 之间你有一个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>

【讨论】:

  • 哇,它的表现太棒了,简直不敢相信它这么小!我被困了5天了!!!
猜你喜欢
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
相关资源
最近更新 更多