我使用的是Rails 4。假设我有三个模型:House
、Color
和HouseColoring
。
class House < ActiveRecord::Base
has_many :house_colorings
has_many :colors, through: :house_colorings
accepts_nested_attributes_for :house_colorings, allow_destroy: true
end
class Color < ActiveRecord::Base
has_many :house_colorings
has_many :houses, through: :house_colorings
end
class HouseColoring < ActiveRecord::Base
belongs_to :house
belongs_to :color
end
houses_controller.rb
:
class HousesController < ApplicationController
before_action :set_house
...
def new
@house = House.new
@house.house_colorings.build
end
def create
@house = House.create(house_params)
if @house.save
redirect_to @house
else
render 'new'
end
end
def edit
#Gets @house from set_house
end
def update
if @house.update(house_params)
redirect_to @house
else
render 'edit'
end
end
...
private
def set_house
@house = House.find(params[:id])
end
def house_params
params.require(:house).permit(:some_parameters, house_colorings_attributes: [:id, :color_id])
end
end
这是我的
_form.html.erb
片段,用于房屋new
和edit
。<%= form_for @house do |f| %>
<div id="house_colorings">
<%= f.fields_for :house_colorings do |c| %>
<%= render "house_colorings", f: c %>
<% end %>
<%= link_to "Add color", add_color_path, remote: true %>
</div>
<% end %>
_house_colorings.html.erb
:
<%= f.collection_select :color_id, Color.all, :id, :name, {include_blank: "Select color"} %>
在
houses_controller
中,我已添加:def add_color
respond_to do |format|
format.js
end
end
add_color.js.erb
:
$("#house_colorings").append("<%= escape_javascript render 'house_colorings', f: c %>");
我为我的add_color
方法添加了一条路由:
GET "/add_color" => "houses#add_color"
当我点击我的“添加颜色”链接时,屏幕上没有任何反应,但是在我的日志中出现了“500内部服务器错误”。
Started GET "/add_color" for 127.0.0.1 at 2013-10-26 21:11:41 -0700
Processing by HousesController#add_color as JS
Rendered houses/add_color.js.erb (11.3ms)
Completed 500 Internal Server Error in 14ms
ActionView::Template::Error (undefined local variable or method `f' for #<#<Class:0x007fc317428538>:0x007fc31710d060>):
1: $("#house_colorings").append("<%= escape_javascript render 'house_colorings', f: c %>");
app/views/houses/add_color.js.erb:1:in `_app_views_houses_add_color_js_erb__1847085463095078116_70237941180700'
目前,我只有一个字段来为我的房子添加颜色。我想添加一些ajax,并在表单中添加一个链接,在已有的字段后面添加一个新的字段,但我不确定如何做到这一点。
我已经浏览了Railscasts中的“嵌套模型表单”并使用其中的部分内容来达到我现在的状态,但如果可能的话,我想使用Rails提供的“data_remote”帮助程序。我编辑了我的问题并包括了当我点击添加颜色链接时出现的错误日志。我相当确信我需要更改我的
add_color.js.erb
或我的houses控制器中的add_color
操作。有什么建议吗?
add_house_coloring.js.erb
或我的houses控制器中的add_house_coloring
操作之一。 - oobie11locals: {f:c}
而不是只用f:c
。 - Almaronadd_color.js.erb
和_form.html.erb
中分别或一起替换f: c
为locals: {f: c}
,但日志中仍然出现相同的500错误。您还有其他想法吗? - oobie11@house.house_colorings.build
这样的代码不起作用。 - oobie11