Rails 表单“必须存在"协会 [英] Rails Form "Must exist" Association

查看:48
本文介绍了Rails 表单“必须存在"协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用简单表单 gem 创建了此表单,用于论坛的帖子类:

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:

表单错误图像

我不知道如何进行,因为这些对象(C、C++ 等)都存在.这是它们的创建位置,位于 seeds.rb

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')

是的,我确实运行了 rake db:seed 并在尝试之前重新启动了服务器.

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

推荐答案

这与语言级别的对象模型关系不大,并且是特定于框架/orm 的.belongs_to Rails 5 中的关联默认是非可选的.

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

如果 post.category_id 为零,您将收到验证错误.例如,如果您忘记将 category_id 属性列入白名单,就会发生这种情况.

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

此外,您可以将 category 关联声明为可选:

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

这篇关于Rails 表单“必须存在"协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆