This is my controllers and routes I have a albums controller and a bands controler with their models, and I want to access the foreign key to pass it, but it told me bands is blank
def show
@album = Album.find_by(:id => params[:id])
render :show
end
def new
@band = Band.find_by(:id => params[:band_id])
@albums = Album.new(:band_id => params[:band_id])
render :new
end
def create
@albums = Album.new(albums_params)
if @albums.save
flash[:success] = "Album created successfully"
redirect_to album_path(@albums.id)
else
@band = @albums.band
flash[:error] = @albums.errors.full_messages
render :new
end
end
def update
render :edit
end
def edit
end
def destroy
end
private
def albums_params
params.require(:albums).permit(:name, :band_id, :live, :year)
end
end```
resources :bands do
resources :albums, :only => :new
end
CodePudding user response:
Try to pass Band relation like below.
def new
@band = Band.find_by(:id => params[:band_id])
@albums = Album.new(:band => @band)
render :new
end
OR check your code. Can you find Band with correct id?
@band = Band.find_by(:id => params[:band_id])
AND check your Views You must put someting like below
<%=form.hidden_field :band_id, value: @albums.band_id%>
OR
<%=form.hidden_field :band_id, value: @band.id %>