我在 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"
当我点击我的add color
链接时,屏幕上什么也没有发生,但在我的日志中我得到一个500 internal server error
.
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'
到目前为止,我只有一个字段可以为我的房子添加 house_coloring。我想添加一些 ajax,并在我的表单中有一个链接,该链接在该字段之后添加一个新字段,但我不确定如何执行此操作。
我已经浏览了 Railscasts 的“嵌套模型表单”,并使用其中的一部分来达到我现在的目的,但如果可以的话,我想使用 rails 提供的“data_remote”助手。我已经编辑了我的问题,并包含了我在单击添加颜色链接时遇到的错误的日志。我很确定我需要更改我的add_color.js.erb
或add_color
我的房屋控制器中的操作。
有什么建议么?