Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Form "Must exist" Association

I created this form, using simple form gem, for a post class of a forum:

<%= simple_form_for @post do |p| %>
  <%= p.input :title, label: false, placeholder: 'Title', required: true %>
  <%= p.input :description, as: :text, label: false, placeholder: 'Describe your post', required: true %>
  <%= p.association :category, label: false, required: true,
  collection: Category.order(:title), prompt: 'Choose category' %>
  <%= p.button :submit %>
<% end %>

Now I go to the page and try to create a post and I get this:

Image for Form Error

I have no idea how to proceed since this objects (C, C++, etc) all exist. Here is where they were created, in seeds.rb

c1 = Category.create(title: "C++", image_url: 'http://www.freeiconspng.com/uploads/c--logo-icon-0.png')
c2 = Category.create(title: "Rails", image_url: 'http://perfectial.com/wp-content/uploads/2015/02/ruby.png')
c3 = Category.create(title: "Python", image_url: 'http://python.net/~goodger/projects/graphics/python/newlogo-repro.png')
c4 = Category.create(title: "Cobol", image_url: 'http://insights.dice.com/wp-content/uploads/2013/06/cobol.png')
c5 = Category.create(title: "C", image_url: 'https://d13yacurqjgara.cloudfront.net/users/28449/screenshots/1040285/cap-logo-ideas3.png')
c6 = Category.create(title: "Perl", image_url: 'http://news.perlfoundation.org/onion_logo.png')

And yes, I did run rake db:seed and restarted the server before trying it.

like image 846
Vitor Falcão Avatar asked Dec 02 '22 14:12

Vitor Falcão


1 Answers

This has very little to do with the language level object model and is framework/orm specific. belongs_to associations in Rails 5 default to being non optional.

So if you for example have this setup:

class Post
  belongs_to :category
end

class Category
  has_many :posts
end

You will get a validation error if post.category_id is nil.This can happen example if you have forgotten to whitelist the category_id attribute.

def post_attributes
  params.require(:post).permit(:title, :description, :category_id)
end

Additionally you can declare the category association as optional:

class Post
  # this was the default behavior in Rails 4
  belongs_to :category, optional: true
end
like image 119
max Avatar answered Dec 21 '22 23:12

max