2016-09-05 1 views
0

Проблема:RoR - Запись не удалось сохранить, когда после того, как его внешний ключ был установлен в ноль

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. 

Часть контроллера:

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 

Мои попытка: разрешить параметры, такие как местоположение и изображение в моем методе редактирования. Как это было предложено на Can't update my nested model form for has_one association

Я попытался

'params.require(:...).permit(...)' 

и

accepts_nested_attributes_for(:..., update_only: true) 

решение, которое было предложено. Но даже со всеми параметрами, позволяющими это не получилось. Знаете ли вы, почему? Я пытался изменить методы, но о хорошо ...

Edit - - Модель:

class Location < ApplicationRecord 
    belongs_to :owner, class_name: '::User', foreign_key: 'owner_id' 
    has_one  :address, as: :addressable, :dependent => :destroy 
    has_one  :image, as: :visualisable 
    has_many :events 

    validates_presence_of :owner_id, :name 

    def display_name 
    [name.to_s, address&.display].compact.join(', ') 
    end 

    def self.all_as_select_options 
    all.collect { |m| [m.name, m.id] } 
    end 

    def can_be_deleted_by?(user) 
    owner == user && events.count == 0 
    end 
end 

ответ

0

Вы пытаетесь удалить изображение? Потому что Failed to remove the existing associated image. так говорит.

Если да, попробуйте добавить accepts_nested_attributes_for(:..., allow_destroy: true) в вашу модель Location.

+0

Благодарим вас за ответ! Я попытался добавить accepts_nested_attributes_for (: image, allow_destroy: true), но почему-то это не сработало. Да, я пытаюсь удалить его. Я знаю, что мне нужно использовать allow_destroy, но я получаю еще больше ошибок, когда я помещаю его в модель. – Tzio

+0

Можете ли вы приложить содержимое своей модели «Местоположение» к вопросу? –

+0

И какая именно ошибка возникает при добавлении «allow_destroy»? Вы также добавляете параметр ': _destroy' в' params.require' так: '' 'params.require (: location) .permit (some_location_params, image_attributes: [: file,: _destroy])' '' –

Смежные вопросы