Hi I am having trouble with creating association using simple_form. Model Chapter belongs to Subject:
class Subject < ActiveRecord::Base
validates :name, :presence => true,
:length => {:maximum => 30},
:uniqueness => true
has_many :chapters
end
Model for Chapter:
class Chapter < ActiveRecord::Base
validates :name, :presence => true,
:length => {:maximum => 80}
validates :subject_id, :presence => true
belongs_to :subject
end
Controller for Chapter
def new
@chapter = Chapter.new
end
def create
@chapter = Chapter.new(chapter_params)
if @chapter.save
flash[:notice] = "Chapter created successfully."
redirect_to(:action => 'index')
else
render('new')
end
end
private
def chapter_params
params.require(:chapter).permit(:name, :permalink, :subject_id,
:introduction, :free, :active, :position, :semester)
end
Form for new Chapter
<%= simple_form_for(:chapter, :url => {:action => 'create'} ) do |f| %>
<%= f.input :name %>
<%= f.input :permalink} %>
<%= f.association :subject %>
<%= f.input :introduction %>
<%= f.input :free, as: :radio_buttons%>
<%= f.input :active, as: :radio_buttons %>
<%= f.input :position %>
<%= f.input :semester %>
<%= f.button :submit, value: 'Save Chapter' %>
I get following error:
"Association cannot be used in forms not associated with an object."
Is there anything I need to add to my controller or model? When I don't use association and simply input the ID of subject, everything works.
You need to add to the Chapter model the following code
accepts_nested_attributes_for :subject
Update
Since the Subject Model is the parent of the Chapter model, the solution described before won't work. accepts_nested_attributes_for only works in the "has_many" model and not in the "belongs_to" model. I'm leaving it here for reference.
In order to make the form builder know how about the association, you need to add to your controller "new" method the following code:
@chapter.build_subject
You will also need to change the simple_form_for call from:
simple_form_for(:chapter, :url => {:action => 'create'} ) do |f|
to:
simple_form_for @chapter do |f|
Because you need to pass the object you created to your form, and you're not doing that using a symbol in the simple_form_for call.