Search code examples
ruby-on-railsrubyruby-on-rails-5simple-formsimple-form-for

Using Simple form gem f.association gives NoMethodError for new action


I am creating a website that allows people to post ads. In creating a new ad, I want them to select a category for that ad from a prepopulated list in my seeds.rb. So I've made the following models and associations.

app/models/ad.rb

class Ad < ApplicationRecord
  # validations
  belongs_to :category
end

app/models/category.rb

class Category < ApplicationRecord
  has_ancestry
  extend FriendlyId
  friendly_id :name, use: :slugged

  has_many :ads
end 

Then I modified my Ad form, using simple form, to use f.association :category to generate a selection from the pre-populated categories listing (See below)

app/views/ads/new.html.erb

<%= simple_form_for @ad, url: ads_path do |f| %>
  <%= f.input :title, label: false, placeholder: "Item/Service for Sale" %>
  <%= f.association :category, label_method: :name, value_method: :id %>
  # other stuff 
<% end %>

I continue to get the following error: "NoMethodError in Ads#new: undefined method `category_id' for # Did you mean? category category="

Any idea what the problem can be? Also, here's the new and create actions in my Ads controller:

class AdsController < ApplicationController
  before_action :authenticate_user!, only: [:new, :create] 

  def new
    @ad = Ad.new
  end 

  def create
    @ad = current_user.ads.create(ad_params)
    if @ad.valid?
      flash[:notice] = "Ad created successfully"
      redirect_to ad_path(@ad)
    else
      render :new, status: :unprocessable_entity
    end 
  end 

  # other actions 


  private

  def ad_params
    params.require(:ad).permit(:title, :cost, :description, :quantity, :phone, :email, :accepted)
  end 
end 

Some help in getting this form to work would be appreciated!


Solution

  • Maybe you are missing the category_id in Ads table

    Although an Ad belongs_to :category, if you have not set a category_id column on your Ads table it will not work.

    If you need to add this column you should create a migration

    class AddCategoryToAds < ActiveRecord::Migration
      def change
        add_reference :ads, :category, index: true
      end
    end
    

    This migration can be automatically created using:

    rails g migration AddCategoryToAds category:references
    

    Finally, allow category_id as a parameter:

    def ad_params
      params.require(:ad).permit(:title, :cost, :description, :quantity, :phone, :email, :accepted, :category_id)
    end