当我提交表单以保存条目时,嵌套值(在Ride模型中)命名为' test'没有得救。
我的entry_params方法是否正确允许嵌套属性通过?在检查输入对象时,我在输入记录中没有ride_id值:
--- !ruby/object:Entry
attributes:
id: 47
show_date: 0008-08-08
user_id:
ride_id:
created_at: 2014-07-04 21:08:49.294361000 Z
updated_at: 2014-07-04 21:08:49.294361000 Z
我有模特:
class Entry < ActiveRecord::Base
has_many :rides, :dependent => :destroy
has_many :horses, :through => :rides, :dependent => :destroy
has_many :riders, :through => :rides, :dependent => :destroy
end
class Ride < ActiveRecord::Base
belongs_to :entry
has_many :horses, :dependent => :destroy
has_many :riders, :dependent => :destroy
end
我的部分输入控制器文件:
class EntriesController < ApplicationController
before_action :set_entry, only: [:show, :edit, :update, :destroy]
def new
@entry = Entry.new
1.times do
@entry.rides.build
end
end
def create
@entry = Entry.create(entry_params)
respond_to do |format|
if @entry.save
format.html { redirect_to @entry, notice: 'Entry was successfully created.' }
format.json { render :show, status: :created, location: @entry }
else
format.html { render :new }
format.json { render json: @entry.errors, status: :unprocessable_entity }
end
end
end
def destroy
@entry.destroy
respond_to do |format|
format.html { redirect_to entries_path, notice: 'Entry was successfully deleted.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_entry
@entry = Entry.find(params[:id])
end
def entry_params
params.require(:entry).permit(:show_date, ride_attributes: [:test])
end
端
我的表单提交具有嵌套属性的条目:
<%= form_for (@entry), :url => entries_path do |f| %>
<p>
<%= f.label :show_date %><br>
<%= f.text_field :show_date %>
</p>
<%= f.fields_for :rides do |builder| %>
<p>
<%= builder.label :test %><br>
<%= builder.text_field :test %>
</p>
<% end %>
<p>
<%= f.submit %>
</p>
<% end %>
答案 0 :(得分:0)
问题是您 accepts_nested_attributes_for :rides
模型中缺少 Entry
。
class Entry < ActiveRecord::Base
has_many :rides, :dependent => :destroy
has_many :horses, :through => :rides, :dependent => :destroy
has_many :riders, :through => :rides, :dependent => :destroy
accepts_nested_attributes_for :rides
end
来自 API
嵌套属性允许您保存关联记录的属性 通过父母
因此,在您的情况下, rides_attributes
未保存,因为您的 {中没有 accepts_nested_attributes_for :rides
{1}} 模型
此外 Entry
应该如下所示
entry_params
您有 def entry_params
params.require(:entry).permit(:show_date, rides_attributes: [:test])
end
,因此 has_many :rides
不是 rides_attributes
。