我正在編寫一個應用程序,它允許用戶將一個組件添加到我的數據庫中的特定頁面,但是我被困在了一點JS上。Rails和Ajax表單提交
我的表單提交得很好。我堅持如何「刷新」顯示與頁面關聯的所有當前組件的容器div。
我來自PHP的背景,所以我知道我可以在我的模型中編寫一個方法,並對其進行ajax調用,並使用jQuery重新填充容器div。我如何在Rails中做到這一點?或者有更好的方法來做到這一點?
形式:
<div class="add_component_block" style="display: none">
<%= form_for page, :url => page_url(page), :class => "edit_page" do |p| %>
<div class="field">
<%= select_tag :component_id, options_for_select(@components.collect { |comp| [comp.name, comp.id] }), :include_blank => 'Select a Component' %>
</div>
<div class="action">
<%= p.submit :Submit %>
</div>
<% end %>
</div>
的jQuery:
$('#page_submit').click(function(e){
$.ajax({
url: $('.edit_page').attr('action'),
type: "PUT",
data: "component_id=" + $('#component_id').val(),
success: function(data){
location.reload();
}
});
return false;
});
在此先感謝您的幫助!
工作守則
控制器:
def create
if !params[:component_id]
@component = Component.new(params[:component])
respond_to do |format|
if @component.save
params[:page_id].each { |p|
PagesComponent.create({ :page_id => p, :component_id => @component.id })
} unless params[:page_id].nil?
format.html { redirect_to(@component, :notice => 'Component was successfully created.') }
format.xml { render :xml => @component, :status => :created, :location => @component }
else
format.html { render :action => "new" }
format.xml { render :xml => @component.errors, :status => :unprocessable_entity }
end
end
else
@component = PagesComponent.new(:page_id => params[:page_id], :component_id => params[:component_id])
if @component.save
@all_components = Page.where("id = ?", params[:page_id])
@component_list = []
@all_components.each do |pc|
pc.components.each do |c|
@component_list << c.name
end
end
render :json => @component_list
end
end
end
的jQuery:
$('#page_submit').click(function(){
$('.add_component_block').hide();
$.ajax({
url: $('.edit_page').attr('action'),
type: "POST",
data: "component_id=" + $('#component_id').val(),
success: function(data){
console.log(data)
$('#page_components').empty();
$.each(data, function(i, itemData){
$('#page_components').append("Name: " + itemData + "<br />")
});
}
});
return false;
});
感謝您的幫助!我把我的編輯放在了我最終做的事情上......但是,我有一個新問題。當帖子完成後,我用重新寫入的數據重寫我的HTML,但返回的列表按照名稱與數據庫中的順序分組在一起......無論如何要解決這個問題?我的代碼也包含在上面 – dennismonsewicz 2010-10-18 20:26:41
很難知道你的模型是什麼樣子,但是有可能自然和字母順序巧合地相同嗎?除非您指定:order參數,否則Rails不會更改結果集的順序。看看你的日誌/ development.log,你可以檢查正在使用的SQL。順便說一句:恭喜你到了這一步。你做得很好。 – 2010-10-19 02:07:25