【问题标题】:How to insert into table using link tag如何使用链接标签插入表格
【发布时间】:2012-02-06 13:42:18
【问题描述】:

我有ArtistProduct 模型。用户输入产品详细信息,用户可以在保存详细信息前单击预览链接在模态窗口中查看输入的详细信息。

我正在尝试使用 AJAX 保存数据,方法是在验证时传递参数等所有详细信息,但它不保存数据库。

鉴于我正在调用 AJAX:

var theVal=id+'/'+artist_id+'/'+name+'/'+desc+'/'+price+'/'+story+'/'+artist_name+'/'+dimension+'/'+material+'/'+contact
var theURL = '/add_temp/' + theVal;
$.ajax({
  url: theURL
});

在控制器中我是这样处理的:

def add_temp
  @pro_id=ArtistProduct.where("id=?",params[:id])
  if @pro_id.nil?
    @artistprod = ArtistProduct.new(:artist_id=>58, :product_name=>params[:name], :description=>params[:desc], :product_price=>params[:price], :product_story=>params[:story],:artist_name=>params[:artist_name], :dimensions=>params[:dimension],:material=>params[:material],:contact_number=>params[:contact])
    @artistprod.save
  end 
end

更新

感谢您的回复。

现在出现路由错误。

在我的路由器中,我喜欢:

match 'add_temp/:id/:artist_id/:name/:desc/:price/:story/:artist_name/:dimension/:material/:contact'=> 'artist_products#add_temp'

更新

路由错误

找不到404

没有路线匹配 [POST] "/add_temp/P58018/58/Prod/swsx/50/sfdf/null/null/0"

更新

是的,我识别并纠正了它,但值仍然没有保存到数据库中。请帮帮我

在控制器中我这样做:

def add_temp if !(ArtistProduct.where("id=?",params[:id]).exists?) @artistprod=ArtistProduct.new(:id=>params[:id],:artist_id=>58, :product_name=>params[:name], :description=>params[:desc], :product_price=>params[: price], :product_story=>params[:story],:artist_name=>params[:artist_name], :dimensions=>params[:dimension],:material=>params[:material],:contact_number=>params[:接触]) @artistprod.save respond_to 做 |格式| format.html { redirect_to @artistprod.addproduct } 格式.js 结尾 结尾 结尾

您好 dbkooper,感谢您的回答。我尝试了你给出的答案,但出现路由错误 在视图中调用如下:

var theURL = '/artist_products/'+id+'/add_temp?artist_id='+artist_id+'product_name='+name+'description='+desc+'product_price='+price+'product_story='+story+'artist_name='+artist_name+'尺寸='+尺寸+'材料='+材料+'contact_number='+接触;

【问题讨论】:

  • 您需要提供服务器日志中显示的确切错误。
  • 你有 9 个参数要传入,但路由希望你传入 10 个参数。

标签: ruby-on-rails ajax


【解决方案1】:

我看到的最大问题是您的$.ajax 呼叫缺少一些选项。默认情况下,如果未指定类型,$.ajax 默认为 GET 请求。

你应该把它改成:

$.ajax({
  type: 'POST',
  url: theURL,
  success: function (json) {
    // handle your success here
  },
  error: function (response) {
    // handle your errors here
  }
});

这样,您指定它将是一个POST 请求,并且您还有处理successerror 的回调方法

【讨论】:

  • 非常感谢。现在值已成功保存在数据库中。
  • 很高兴为您提供帮助!请单击我的答案旁边的复选标记以关闭问题
【解决方案2】:

我认为你的路线应该是

resources artist_products do 
    member do 
         post 'add_temp' 
     end
end

使用 rake :routes 获取正确的路由 最有可能是“artist_products/:id/add_temp”

对于 ajax 请求,您可以发送 val 参数的 using ?到网址 喜欢

var theURL = '/artist_products/'+id+'/add_temp?artist_id='+artist_id+'so on..'; 
$.ajax({   url: theURL });

在您的控制器内部 你可以像往常一样访问参数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多