Search code examples
ruby-on-railsmodels

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


I have a Post model and Summary model where a post has only one model.

#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

When I try to create a post with a summary, by clicking save button is a standard form, something in my view causes an error.

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>

Apparently, I'm not able to call summary on my post. Because summary is its own class, I'm having trouble with my variables in the view above and the corresponding controllers.

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

Do I have the names mixed up? How should I be joining these two models to create and display a summary for for a new post?


Solution

  • Try this instead:

    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