2016-06-06 2 views
1

У меня есть модель recipient и category. В простой ассоциации 1 категории есть много получателей. Когда я пытаюсь обновить форму recipient и назначить category, она не будет сохранена в записи. Если я использую консоль и обновляю запись вручную, например. Recipient.update(9, category_id: 13), я вижу правильную категорию, назначенную получателю, но когда я пытаюсь отредактировать/обновить запись, она не будет сохранена в новой выбранной категории.ассоциация simple_form не сохраняет own_to id

Вот моя recipient модель

class Recipient < ActiveRecord::Base 
    belongs_to :category 

    accepts_nested_attributes_for :category 
end 

Вот моя category модель

class Category < ActiveRecord::Base 
    has_many :recipients 
    validates :category, presence: true 

    default_scope { order('category')} 
end 

вот recipient контроллер

class RecipientsController < ApplicationController 
    def index 
    @recipients = Recipient.order(:recipient_name).page(params[:page]) 
    end 

    def new 
    @recipient = Recipient.new 
    end 

    def show 
    @recipient = Recipient.find(params[:id]) 
    end 

    def create 
    @recipient = Recipient.new(recipient_params) 
    if @recipient.save 
     redirect_to recipients_path 
    else 
     render :new 
    end 
    end 

    def edit 
    @recipient = Recipient.find(params[:id]) 
    end 

    def update 
    @recipient = Recipient.find(params[:id]) 

    recipient_params = params.require(:recipient).permit(:recipient_name, :alternate_name, :description, :city, :state, :country, category_attributes: [:category, :id]) 
    @recipient.update_attributes(recipient_params) 

    redirect_to recipient_path(id: @recipient.id) 
    end 

    def destroy 
    @recipient = Recipient.find(params[:id]) 
    @recipient.destroy 

    redirect_to recipients_path 
    end 

    private 
    def recipient_params 
    params.require(:recipient).permit(:recipient_name, :alternate_name, :description, :city, :state, :country, product_attributes: [:product_name, recipient_products: [:recipient_id, :product_id]], channel_attributes: [:channel_name, recipient_channels: [:recipient_id, :channel_id]], category_attributes: [:id, :category]) 
    end 

end 

вот edit вид

<div class="row"> 
    <div class="col-sm-6"> 
    <h2>Edit <%= @recipient.recipient_name %></h2> 

    <%= simple_form_for @recipient do |form| %> 
     <%= form.error_notification %> 
     <%= form.input :recipient_name, placeholder: 'Recipient', label: 'Recipient Name' %> 
     <%= form.input :alternate_name, placeholder: 'Alternate Name' %> 
     <%= form.association :category, label_method: :category, value_method: :id %> 
     <%= form.input :description, placeholder: 'Description'%> 
     <%= form.input :city, placeholder: 'City'%> 
     <%= form.input :state, placeholder: 'State' %> 
     <%= form.input :country, as: :country, priority: ['US', 'CA'] %> 
     <%= form.button :submit, 'Update Recipient', {:class=>"btn btn-secondary"} %> 
     <%= link_to "Cancel", :back, {:class=>"btn btn-default"} %> 
    <% end %> 
    </div> 
</div> 

и вот мой routes.rb файл

Rails.application.routes.draw do 
    root to: 'home#index' 
    resources :media_points 
    resources :products 
    resources :channels 
    resources :recipients 
    resources :media_point_products 
    resources :distributions 
    resources :categories do 
    resources :recipients 
    end 
    get '/listing' => "listing#index" 
    devise_for :admins 
    devise_for :users 
    resources :users 
end 
+0

Я считаю, вам нужно изменить метод params в вашем контроллере. Попробуйте изменить: category_attributes: [: category,: id] to category_id:: category_id_from_form_here – bkunzi01

ответ

0

Я написал его в качестве ответа, так как формат является боль в комментариях:

Меняйте recipient_params частный метод из: category_attributes: [:category, :id]

до

category_id: param_that_has_category_id_here 

Кроме того, у вас есть два маршрута для получателей, и он будет использовать первый сопоставленный маршрут, который не является вложенными получателями в маршрутах категорий, в которых вы находитесь дальше. Если первые изменения в вашем частном методе не исправить, я бы указать вложенную ситуацию в simpleform делать так, так как вы, вероятно, хотите использовать вложенную маршрут:

simple_form_for [@category, @recipient], url: 'nested_route_path_here' do |f| 

Просто добавьте @category = Category.new к новому действию в контроллер получателей, а затем в вашем действии на создание вы получите параметр категории, отправленный через params [: category_id]

+0

Я понимаю большую часть вашего ответа, но теряюсь в правильном синтаксисе для 'category_id: param_that_has_category_id_here' Я не уверен, что поставить для' param_that_has_category_id_here' – awkale

+0

Ваша форма отправляет значение для идентификатора категории, любой атрибут, который вы указали в своей форме, для этого значения должен быть включен в белый список в ваш метод params и присвоен «category_id», поэтому Rails правильно обрабатывает ассоциацию. – bkunzi01