【发布时间】:2018-08-04 15:29:27
【问题描述】:
我到处寻找答案,但没有一个对我有用(我可能做错了什么)。
我对 Ruby/Ruby on Rails 很陌生,所以我不太了解它是如何工作的。
我的应用程序中有两个模型
Attribute name:string和;Product name:string.
我也有两个控制器:
attributes_controller和;products_controller.
我也有以下观点../app/views/product_models/new.html.erb。在这个视图中,我希望能够创建一个属性并在之后立即将其显示给用户(使用 AJAX)
<div id="attributes_list">
<%= render :partial => "attributes/attribute", :collection => @attributes, :as => :attribute %>
</div>
<div id="new_attribute">
<strong>Adicionar novo atributo</strong> <br />
Nome: <input type="text" class="name"><br />
<span class="create_button">Criar</span>
</div>
对于这种情况,我有以下jquery(../app/assets/javascripts/application.js):
$(document).ready(function () {
var new_attribute_div = $(document).find('#new_attribute')
new_attribute_div.on('click', '.create_button', function () {
// alert('funfou');
$.ajax({
url: '/attributes',
type: 'POST',
dataType: "script",
data: {
name: new_attribute_div.find(".name").val()
},
success: function (data) {
$(document)
.find('#attributes_list')
.append("<%= j render @attribute %>");
new_attribute_div.find(".name").val("");
},
error: function (data) {
alert("error:" + data)
}
});
});
});
而我的 attributes_controller 就是这样的
class AttributesController < ApplicationController
def create
@attribute = Attribute.new(attribute_params)
@attribute.save
respond_to do |format|
format.html { redirect_to @attribute }
format.js
format.json
end
end
end
private
def attribute_params
params.permit(:name)
end
我遇到的问题是,当执行 jquery 的以下行时
.append("<%= j render @attribute %>");
rails 不是渲染属性的一部分,而是渲染字符串本身()
我做错了什么? 如何渲染从控制器返回的@attribute?
【问题讨论】:
标签: jquery ruby-on-rails ajax model-view-controller partials