So I have a nested resource with
resources :albums do
resources :elements
end
I can update, delete and view those elements.
What I can not really do is to create a new element.
So it is actually created in the database but not in the mapping table.
Models:
class Album:
has_many :elements, :through => :albums_elements
has_many :albums_elements
class Element:
has_many :albums_elements
has_one :album, :through => :albums_elements
class AlbumsElement:
belongs_to :album
belongs_to :element
In the element Controller I have:
def create
@element = Element.new(params[:element])
@album = Album.find(params[:album_id])
respond_to do |format|
if @element.save
format.html { redirect_to album_elements_path(@album), :notice => 'Element was successfully created.' }
format.json { render :json => @element, :status => :created, :location => @element }
else
format.html { render :action => "new" }
format.json { render :json => @element.errors, :status => :unprocessable_entity }
end
end
end
So as I said, when I press the create button in the form, the element is being created correctly in the table “elements”, but not inserted into “albums_elements”.
I saw a similar post here, where the author was told to fix his dependencies.
But I don’t see an error in mines?
How do I tell rails to insert into both tables?
elements AND albums_elements?
Would you please check by relating your
@elementand@albuminelements_controllerclass? Like you already haveJust add
Now
@element.saveshould insert a entry in your relationship table also.Let me know if it works. I’ve just answered after a glance to the problem.
Clarifications:
I will try to make a sample app for you. But before that i need to know some more.
Seems the relationship between
AlbumandElementisone-to-many, then why you are usinghas_many :through? It could be simplyAlbum: has_many :productsandProduct: belongs_to :album.If you must use a relationship table, does it have any other attributes?
Is it OK if I provide any solution of
one-to-many?I will try to provide you the best rails way to save these entries asap.
Thnx