Hello everyone,
I’m currently working on the functionality that users can create
listings that are than saved in categories. I created tables and
relationships but I cannot get the listings do be saved in the
categories.
Here is what I have:
Model category.rb
class Category < ActiveRecord::Base
has_many :listings
end
model listing.rb
class Listing < ActiveRecord::Base
belongs_to :user
belongs_to :category
default_scope -> { order(‘created_at DESC’) }
validates :location, presence: true, length: { maximum: 20 }
validates :title, presence: true, length: { maximum: 20 }
validates :user_id, presence: true
validates :description, presence: true
end
Listings controller
def new
@listing = Listing.new
@listings = Listing.paginate(page: params[:page])
@categories = Category.all
end
def create
@listing = current_user.listings.build(listing_params)
@categories = Category.all
if @listing.save
flash[:success] = “Job Post created”
redirect_to current_user
else
render ‘listings/new’
end
end
Views categories/new
New category
<%= render ‘form’ %>
<%= link_to ‘Back’, categories_path %>
Views categories/_form.html.erb
<%= form_for(@category) do |f| %>
<% if @category.errors.any? %>
<%= pluralize(@category.errors.count, “error”) %> prohibited
this category from being saved:
<ul>
<% @category.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :name %>
Views Listing/new.html.erb
Create Job Post
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :location %>
<%= f.text_field :location %>
<br>
<%= f.text_area :description, placeholder: "Compose new
listing…", class: “description_form” %>
Category:
<% @categories.each do |category| %>
>
<%= category.name %>
<% end %>
<% end %>
I have a listings table with the following columns:
id title description location user_id created_at updated_at category_id
and categories table
id name created_at updated_at
When I create a new listing and than check the listings table, the
category_id field is blank.
Does anyone know why my listings are not saved in the categories?
Thank you very much