我正在尝试将数据从使用 Ruby on Rails 构建的表单插入到我的 SQL Server 数据库中。我已经正确连接了我的数据库并且可以从中提取数据。我现在正试图回发给它。我需要帮助来弄清楚如何将表单中的数据放入数据库表中的正确列中。
我的 Ajax :
<script>
$('#Favorites').on('submit',function(event){
var $form = $(this),
data = $form.serialize();
var url = 'http://localhost:3000/welcome/insert';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(){
alert('Your form has been successfully submitted!');
document.getElementById('Favorites').reset();
window.location.reload();
},
fail:function(){
alert('something went wrong...try again');
}
});
return false;
});
</script>
我的 Controller 功能:
def insert
@ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link)
values ('I am cool','www.google.com')")
end
目前,我这里只有一个虚拟插入语句,以确保我可以插入到表中,而且我可以。我只需要知道如何分解发送到 Controller 的表单值以及如何告诉 Rails 将这些值放入哪个表和列中。
最佳答案
Rails 将 format the data for you .在这样的 Controller 中:
{'Report_Name': 'some name', 'Report_link': 'www.example.com'}
并且可以通过params
访问。
您现在的工作是为手动执行 SQL 查询正确格式化数据。
insert_values = "('%s', '%s')" % params['Report_Name'], params['Report_link']
@ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link) values #{insert_values}")
关于ruby-on-rails - ajax 从 Rails 应用程序发布到外部数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47063479/