Creating a new post returns a NoMethodError: undefined method `summary' for #<Post::ActiveRecord_Associations_CollectionProxy:0x007ff7fdcafd80>

Creating a new post returns a NoMethodError: undefined method `summary' for #<Post::ActiveRecord_Associations_CollectionProxy:0x007ff7fdcafd80>

我有一个 Post 模型和一个摘要模型,其中 post 只有一个模型。

#Post Model
class Post < ActiveRecord::Base
has_one :summary, dependent: :destroy

default_scope { order('rank DESC') }
    scope :visible_to, -> (user) { user ? all : joins(:topic).where('topics.public' => true ) }

    validates :title, length: {minimum: 5}, presence: true
    validates :body, length: {minimum: 20}, presence: true
    validates :topic, presence: true
    validates :user, presence: true

#Summary Model
class Summary < ActiveRecord::Base
belongs_to :post

validates :body, length: { maximum: 100 }, presence: true
end

当我尝试创建带有摘要的 post 时,通过单击保存按钮是一种标准形式,我认为某些东西会导致错误。

undefined method `summary' for #<Post::ActiveRecord_Associations_CollectionProxy:0x007ff7fdcafd80>


<div class="row"> <!-- what others are there besides row? -->
    <div class="col-md-12">
    <div class="pull-right">
      <h1><%= markdown @post.title %></h1> 
      <h4><%= markdown @post.summary.body %></h4> ** Its the summary in this line **
      <%= render partial: 'votes/voter', locals: { post: @post } %>
          <p><%= markdown @post.body %></p>
          <p><%= image_tag @post.image.url(:thumb) if @post.image? %></p>
     </div>
  </div>

显然,我无法在 post 上调用摘要。 因为摘要是它自己的 class,所以我在上面的视图和相应的控制器中遇到了我的变量问题。

class Topics::PostsController < ApplicationController 
def create
    @topic = Topic.find(params[:topic_id])
    @post = current_user.posts.build(post_params)
    @post.topic = @topic 
    @summary = @post.build(summary_params)
    @summary = @post.summary
    authorize @post

    if @post.save && @summary.save
        @post.create_vote
      flash[:notice] = "Post was saved."
      redirect_to [@topic, @post]
    else
      flash[:error] = "There was an error saving the post. Please try again."
      render :new
    end
  end

我把名字弄错了吗?我应该如何加入这两个模型来创建和显示新 post 的摘要?

试试这个:

def create
  @topic = Topic.find(params[:topic_id])
  @post = current_user.posts.build(post_params)
  @post.topic = @topic       
  authorize @post

  if @post.save
    @summary = @post.build_summary(summary_params)
    if @summary.save
      @post.create_vote
      flash[:notice] = "Post was saved."
      redirect_to [@topic, @post]
    end
  else
    flash[:error] = "There was an error saving the post. Please try again."
    render :new
  end
end