2014-10-16 75 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