0

I'm following the instructions as I understand them. I feel like I have done everything correct, yet something isn't because it's not working. If someone could please take a minute to explain this to me.

I have a Blog#model and a Post#model like this:

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

In my blog#controller

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

In my form:

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

The error I get is:

undefined method `build' for nil:NilClass

I followed instructions from here: http://guides.rubyonrails.org/association_basics.html -- What am I doing wrong?

MrPizzaFace
  • 7,807
  • 15
  • 79
  • 123

1 Answers1

1

Your action should be

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

See chapter "4.2 has_one Association Reference" in the mentioned guide

gotva
  • 5,919
  • 2
  • 25
  • 35
  • I couldn't figure this out for a while and I just found this same answer here http://stackoverflow.com/questions/2472982/using-build-with-a-has-one-association-in-rails Thank you for your help – MrPizzaFace Oct 16 '14 at 21:13