0

我最近添加了一个新模型 (discussion.rb) 和控制器 (discussions_controller.rb)。我正在尝试让 postcomments 与讨论一起工作。

讨论.rb

class Discussion < ActiveRecord::Base

  belongs_to :user
  has_many :postcomments, dependent: :destroy
  validates :user_id, presence: true
  validates :content, presence: true

  attr_accessible :content, :user_id

  default_scope order: 'discussions.created_at DESC'
end

这是我的路线

resources :discussions, :path => "disc"

resources :users do
  member do
    get :following, :followers
  end
end
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
resources :discussions, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
resources :microposts do
  resources :postcomments
  resources :discussions do
    resources :postcomments
  end
end

这是postcomments模型

class Postcomment < ActiveRecord::Base


  attr_accessible :comment_content

  belongs_to :user
  belongs_to :micropost
  belongs_to :discussion

  validates :comment_content, presence: true
  validates :user_id, presence: true

  default_scope order: 'postcomments.created_at ASC'
end

我正在尝试在视图中使用它,除了标题中发布的错误

<%= form_for([discussion, @comment]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_field :comment_content %>
  </div>
  <div class="ItemContainer">
<div class="ItemInput">
    <button class="btn" type="submit">
    Comment
  </button>
  </div><div class="ItemCommentCount">
<% end %>

它说错误是由这一行引起的

 <%= form_for([discussion, @comment]) do |f| %>

有谁知道我该如何解决这个path问题?

class PostcommentsController < ApplicationController
def create
    @micropost = Micropost.find(params[:micropost_id])
    @comment = Postcomment.new(params[:postcomment])
    @comment.micropost = @micropost
    @comment.user = current_user
    if @comment.save
       redirect_to(:back)
    else
      render partial: 'shared/_postcomment_form', locals: { micropost: @micropost }
    end
  end

def createdisc
    @discussion = Discussion.find(params[:discussion_id])
    @comment = Postcomment.new(params[:postcomment])
    @comment.discussion = @discussion
    @comment.user = current_user
    if @comment.save
       redirect_to(:back)
    else
      render partial: 'shared/_postcomment_form', locals: { discussion: @discussion}
    end
  end

end
4

2 回答 2

0

尝试resources :discussions在您的路线文件中整合您的使用。我在下面进行了编辑,假设您不打算在微博下嵌套讨论。

resources :discussions, only: [:create, :destroy], path: "disc" do
  resources :postcomments
end
resources :users do
  member do
    get :following, :followers
  end
end
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
resources :microposts do
  resources :postcomments
end
于 2013-05-09T03:20:09.317 回答
0

这条线

<%= form_for([discussion, @comment]) do |f| %>

discussion也应该是一个实例变量:

<%= form_for([@discussion, @comment]) do |f| %>

然后你需要在控制器中定义@discussion

于 2013-05-09T03:24:21.107 回答