2016-12-04 32 views
0

我创造了这个形式,使用simple form gem,对后级的论坛:Rails的表“必须存在”协会

<%= 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 %> 

现在我去的网页,并尝试创建一个职位,我得到这个:

Image for Form Error

我不知道如何着手,因为这个对象(C,C++等)的存在。下面是他们创造在哪里,在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') 

是的,我也跑耙分贝:种子,并试图之前重新启动服务器。

回答

4

这与语言级别的对象模型很少有关,并且是框架/ orm特定的。 Rails 5中的belongs_to关联默认为非可选。

因此,如果您例如有这样的设置:

class Post 
    belongs_to :category 
end 

class Category 
    has_many :posts 
end 

你会得到一个验证错误,如果post.category_id是nil.This可能发生的例子,如果你忘记了一个白名单的category_id属性。

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

另外可以声明category协会可选:

class Post 
    # this was the default behavior in Rails 4 
    belongs_to :category, optional: true 
end 
+0

您的意思是'高清post_attributes'? –

+0

是的,做一点点多任务:) – max

+0

另外,你应该在你的'seeds.rb'中使用'.create!' - 如果验证不通过而不是静默地失败,它会引发一个错误。 – max