0

I'm able to get a model Post to be working properly for has_many and accepts_nested_attributes_for model Category. However, I want to limit a post to have only 1 category, which is where I'm failing. Here is the revised code:

# post.rb
has_one :category_tag, :dependent => :delete
has_one :category, through: :category_tag
accepts_nested_attributes_for :category_tag

# posts_controller.rb
def new
  @post = Post.new
  @post.category_tag.build
end

And ^ there is the problem: undefined method 'build' for nil:NilClass
It worked fine when I was using has_many :category_tags in the model and @post.category_tags.build
TIA

1 Answer 1

2

For has_one relationships the correct format is

@post.build_category_tag
Sign up to request clarification or add additional context in comments.

6 Comments

I'm using rails 5 and the solution sounded weird to me, indeed it isn't working.. undefined method build_category_tag
This is very strange! I switched back to has_many settings to continue working on other aspects of the app. However when you posted the answer(which didn't work), I tried the original line(after switching to has_one settings) @post.category_tag.build again and it worked flawlessly. I remember I did restart the server(which shouldn't be a problem in the first place) when I was trying what I posted.
It should've been created. See guides.rubyonrails.org/…
And the guide specifically says you should not use @post.category_tag.build in has_one because it can lead to orphaned records.
I read everything you pointed out. However I'm unable to debug the cause of problem. Can you guide me somehow?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.