2014-10-16 4 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 Ассоциация Reference» в упомянутом guide

+0

Я не мог понять это на некоторое время, и я только что нашел этот же ответ здесь HTTP: //stackoverflow.com/questions/2472982/using-build-with-a-has-one-association-in-rails Благодарим за помощь – fyz

Смежные вопросы