【发布时间】:2016-06-06 22:22:35
【问题描述】:
我有一个 recipient 和 category 模型。这是 1 个类别的简单关联,有许多收件人。当我尝试更新recipient 表单并分配category 时,它不会保存到记录中。如果我使用控制台并手动更新记录,例如Recipient.update(9, category_id: 13),我看到分配给收件人的类别正确,但是当我尝试编辑/更新记录时,它不会保存到新选择的类别。
这是我的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
【问题讨论】:
-
我相信您需要更改控制器中的 params 方法。尝试更改: category_attributes: [:category, :id] to category_id: :category_id_from_form_here
标签: ruby-on-rails associations simple-form