Taylor Mitchell
Taylor Mitchell

Reputation: 613

undefined method `belongs_to' for ActiveRecord:Module

I am getting the following error "undefined method `belongs_to' for ActiveRecord:Module" it is showing the following code for my error in line 1.

class Posting < ActiveRecord::
   belongs_to :user
   validates :content, length: { maximum: 1000 }
end

Also showing an error in this code on line 10

class ProfilesController < ApplicationController

    def show
      if params[:id].nil? # if there is no user id in params, show current one
        @user = current_user
      else
        @user = User.find(params[:id])
      end

      @alias = @user.alias
      @posting = Posting.new
    end

end

The postings controller if it is needed is...

class PostingsController < ApplicationController
  before_action :set_posting, only: [:show, :edit, :update, :destroy]

  # GET /postings
  # GET /postings.json
  def index
    @postings = Posting.all
  end

  # GET /postings/1
  # GET /postings/1.json
  def show
  end

  # GET /postings/new
  def new
    @posting = Posting.new
  end

  # GET /postings/1/edit
  def edit
  end

  # POST /postings
  # POST /postings.json
  def create
    @posting = Posting.new(posting_params)

    respond_to do |format|
      if @posting.save
        format.html { redirect_to @posting, notice: 'Posting was successfully created.' }
        format.json { render action: 'show', status: :created, location: @posting }
      else
        format.html { render action: 'new' }
        format.json { render json: @posting.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /postings/1
  # PATCH/PUT /postings/1.json
  def update
    respond_to do |format|
      if @posting.update(posting_params)
        format.html { redirect_to @posting, notice: 'Posting was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @posting.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /postings/1
  # DELETE /postings/1.json
  def destroy
    @posting.destroy
    respond_to do |format|
      format.html { redirect_to postings_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_posting
      @posting = Posting.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def posting_params
      params.require(:posting).permit(:content, :user_id)
    end
end

Upvotes: 2

Views: 5921

Answers (1)

Niels B.
Niels B.

Reputation: 6310

You need the Posting class to inherit from ActiveRecord::Base and not just ActiveRecord::

Upvotes: 8

Related Questions