user1697061
user1697061

Reputation: 265

Rails has_many belongs_to same form

So I have albums and album_tags. One album can have many album_tags so that I modified the models:

class Album < ActiveRecord::Base
  ...
  has_many :album_tags
end

class AlbumTag < ActiveRecord::Base
  attr_accessible :album_id, :album_tag_id, :tag_name
  belongs_to :album
end

I also added :tag_name to the attr_accessible for albums. But now I need to insert those tag_name into the _form.htl.erb of th albums_views

I did so several times with nested ressources but this time it's different and my ideas did not work out. In my new-method I added

@album_tag = AlbumTag.new

and in my _form.html.erb it looks like this:

<%= f.label :tag_name %><br />
<%= f.text_field :tag_name %>

The log says:

ActionView::Template::Error (undefined method `tag_name' for #<Album:0xe7331c50>):

So I tried to add the album_tag object above:

<%= form_for([@user, @album, @album_tag]) do |f| %>

and then I get:

ActionView::Template::Error (undefined method `user_album_album_tags_path' for #<#<Class:0xe755de48>:0xe755b4cc>):

So my play was to insert a form_field with values like tag1,tag2,tag3 and so on. Afterwards I want to pick them up, and insert them in a for each. But firstly I have to get that field shown without errors. How do I do that ?

Edit: I just tried to add

accepts_nested_attributes_for :album_tags

into my albums_model. Without success

Upvotes: 0

Views: 599

Answers (1)

Ian Armit
Ian Armit

Reputation: 673

This rails cast goes over nested forms fairly well.

http://railscasts.com/episodes/196-nested-model-form-part-1

and part 2:

http://railscasts.com/episodes/197-nested-model-form-part-2

From what I can see, you should be using.

f.fields_for :album_tags do |builder|

Upvotes: 1

Related Questions