Rails form associations for simple_form -
hi having problem creating association using simple_form. model chapter belongs subject:
class subject < activerecord::base validates :name, :presence => true, :length => {:maximum => 30}, :uniqueness => true has_many :chapters end
model chapter:
class chapter < activerecord::base validates :name, :presence => true, :length => {:maximum => 80} validates :subject_id, :presence => true belongs_to :subject end
controller 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 new chapter
<%= simple_form_for(:chapter, :url => {:action => 'create'} ) |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 next error:
"association cannot used in forms not associated object."
is there need add together controller or model? when don't utilize association , input id of subject, works.
you need add together chapter model next code
accepts_nested_attributes_for :subject
update
since subject model parent of chapter model, solution described before won't work. accepts_nested_attributes_for works in "has_many" model , not in "belongs_to" model. i'm leaving here reference.
in order create form builder know how association, need add together controller "new" method next code:
@chapter.build_subject
you need alter simple_form_for phone call from:
simple_form_for(:chapter, :url => {:action => 'create'} ) |f|
to:
simple_form_for @chapter |f|
because need pass object created form, , you're not doing using symbol in simple_form_for call.
ruby-on-rails rails-activerecord simple-form
No comments:
Post a Comment