2014-10-16 42 views
0

我按照我的理解他们的指示。我觉得我已经做了一切正确的事情,但有些事情并不是因为它不工作。如果有人可以请花一分钟向我解释这一点。Rails 4 nested_attributes步行通过

我有一个这样的博客#模型和岗位#型号:

class Post < ActiveRecord::Base 
    belongs_to :blog 
end 
class Blog < ActiveRecord::Base 
    has_one :post, dependent: :destroy 
    accepts_nested_attributes_for :post 
end 

在我的博客#控制器

def new 
    @blog = Blog.new 
    @blog.post.build 
    end 
... 
def strong_params 
    params.require(:blog).permit(:section, :category, :subcategory, :title, post_attributes: [:content]) 
end 

在我的形式:

<%= form_for @blog, url: blog_create_path do |f| %> 
    <%= f.select :section, BlogHelper.sections.unshift('') %> 

    <%= f.fields_for :post do |post_fields| %> 
    <%= post_fields.text_area :content, id: 'blog_content', oninput: "this.editor.update()" %> 
    <% end %> 

    <%= f.submit 'Publish', class: 'btn btn-sm btn-primary' %> 
<% end %> 

错误我得到的是:

undefined method `build' for nil:NilClass 

我按照这里的指示:http://guides.rubyonrails.org/association_basics.html - 我做错了什么?

回答

1

你的动作要

def new 
    @blog = Blog.new 
    @blog.build_post 
end 

参见“4.2 HAS_ONE协会参考”中提到guide

+0

我不知道这一点了一会儿,我刚刚发现这个同样的答案在这里的http: //stackoverflow.com/questions/2472982/using-build-with-a-has-one-association-in-rails谢谢你的帮助 – fyz 2014-10-16 21:13:38