I'm trying to solve this problem of mine. I'll tell you what I did, where I struggle and hopefully you can lend me a hand. I'm kinda new to this Rails thing and get hopefully 1-2 good tips regarding my problem. That would be really awesome.
Problem:
LocationsController request to edit should load the requested location
Failure/Error: @location.image = @image
ActiveRecord::RecordNotSaved:
Failed to remove the existing associated image.
The record failed to save when after its foreign key was set to nil.
LocationsController request to edit should be successfull
Failure/Error: @location.image = @image
ActiveRecord::RecordNotSaved:
Failed to remove the existing associated image.
The record failed to save when after its foreign key was set to nil.
Part of the Controller:
def new
@location = Location.new
end
def create
@location = Location.new(params[:location])
@location.owner_id = current_user.id
@address = Address.new(params[:address])
@location.image = Image.new(params[:image])
responds_to_parent do
if @location.save && @location.image.update_from_uploaded_data(params[:image])
@address.addressable = @location
@address.save
@locations = Location.all_as_select_options
respond_to do |format|
format.js { render layout: false }
end
else
render :update
end
end
end
def edit
@address = @location.address
end
def update
@location.image ||= Image.new
@location.address ||= Address.new
address = params[:address]
if @location.update_attributes(params[:location]) && @location.address.update_attributes(address) && @location.image.update_from_uploaded_data(params[:image])
flash[:notice] = 'Daten für den Ort wurden geändert.'
redirect_to location_path(@location)
else
flash[:notice] = 'Die Daten konnten nicht gespeichert werden'
render action: 'edit'
end
end
def destroy
@location.destroy if @location.owner.id == current_user.id
redirect_to action: 'index', controller: 'locations'
end
private
def load_location
@location = Location.find(params[:id])
end
Rspec:
describe 'request to edit' do
before do
login(mock_admin)
@location = create_location
@image = create_image
Location.stub!(:find).and_return(@location)
Image.stub!(:find).and_return(@image)
@location.image = @image
get :edit, id: @location.id
end
it 'should be successfull' do
response.should be_success
end
it 'should load the requested location' do
assigns(:location).should eql(@location)
end
it 'should load the locations address' do
assigns(:address).should eql(@location.address)
end
end
My attempt: Allowing parameters like location and image in my edit method. Like it was suggested at Can't update my nested model form for has_one association
I tried the
'params.require(:...).permit(...)'
and
accepts_nested_attributes_for(:..., update_only: true)
solution which were suggested. But even with all parameters allowing it didn't work out. Do you knowwhy though? I tried to modify the methods but o well...
Aucun commentaire:
Enregistrer un commentaire