I'm working with rails 5.1.2 and ruby 2.2.6
I have the following classes:
class Idea < ApplicationRecord
validates :title, presence: true
validates :description, presence: false
has_many :discussions
end
class Discussion < ApplicationRecord
validates :title, presence: true
belongs_to :idea
def initialize(title)
@title = title
end
end
At idea creation, I'd like to add a default discussion in the attribute discussions. As I'm a newbie at ruby and rails, I don't know which is the best approach to do this. Here is what I tried unsuccessfully.
In the idea controller, I tried to create the default discussion at the idea creation, as follows:
class IdeasController < ApplicationController
def create
discussion = Discussion.new "Main thread"
@idea = Idea.new(idea_params)
@idea.discussions << discussion
@idea.save
redirect_to ideas_path
end
private
def idea_params
params.require(:idea).permit(:title)
end
end
This drives me to an error in the controller:
undefined method `<<' for nil:NilClass
on the line
@idea.discussions << discussion
I think this is due to an uninitialized discussions array in my idea. However, the guide states that any class that has the declaration has_many would inherit the method <<, as stated in this guide. But maybe this is only true after the idea has been saved at least one time?
I tried manually initialize the array in my controller.
@idea.discussions = []
This helps removing the error, but I'm surprised this is not done automatically. Furthermore, the discussion is not saved in database. I tried adding the declaration autosave in Idea class, with no effect:
has_many :discussions, autosave: true
I'm a little bit lost. At the end, I'd just like to add a discussion in an idea between its creation and save, and persist it. What is the best approach?
Thanks for any help.