使用rails将变量传递到SQL语句中
我试图将变量使用rails将变量传递到SQL语句中,sql,ruby-on-rails,Sql,Ruby On Rails,我试图将变量supplier传递到sql语句的where子句中。它将变量保存为当我单击链接时,它会在url中显示所选供应商。我只是不知道该在语句中添加什么,让它从视图中提取变量 型号: def self.find_supplier find_by_sql(["SELECT s.supplier, s.productcode, s.description, CAST(SUM(l.amount) as UNSIGNED) AS amount FROM softwares s LEFT JOIN li
supplier
传递到sql语句的where子句中。它将变量保存为当我单击链接时,它会在url
中显示所选供应商。我只是不知道该在语句中添加什么,让它从视图中提取变量
型号:
def self.find_supplier
find_by_sql(["SELECT s.supplier, s.productcode, s.description, CAST(SUM(l.amount) as UNSIGNED) AS amount
FROM softwares s
LEFT JOIN licenses l ON s.id=l.software_id
WHERE s.supplier = ? AND l.amount > 0
GROUP BY s.supplier, s.vendor, s.title, s.edition", :supplier)
end
视图:
'软件',:操作=>'出口供应商',:供应商=>l.supplier%>
控制器:
def export_supplier
@software = Software.find_supplier
software = CSV.generate do |csv|
# for the headers of the csv file
csv << ["Quantity", "Item Number", "Item Description"]
# the chosen rows from the database
@software.each do |s|
csv << [s.amount, s.productcode, s.description, s.supplier]
end
end
send_data(software, :type => 'text/csv', :filename => 'software.csv')
end
def出口供应商
@软件=软件。查找供应商
软件=CSV.generate do | CSV|
#用于csv文件的标题
csv“software.csv”)
结束
来自软件
s.id=l.software\U id上的左连接许可证l
其中s.supplier=?和l.amount>0
按s.供应商、s.供应商、s.标题、s.版本分组”,参数[:供应商])
我假设find_by_sql在您的控制器中,“export_supplier”方法。
这里你应该得到params[:supplier]我已经用我的控制器中的代码更新了我的问题,我已经添加了你所说的,我得到了这个错误
未定义的局部变量或方法“params”
模型中无法访问参数,你必须将其作为参数软件传递给模型。查找供应商(params[:supplier])在模型def self.find_supplier(supplier)…end然后你会在模型中有一个供应商变量,而不是:supplier我建议先阅读一些好的rails书籍,比如Obie的rails 3 way
def export_supplier
@software = Software.find_supplier
software = CSV.generate do |csv|
# for the headers of the csv file
csv << ["Quantity", "Item Number", "Item Description"]
# the chosen rows from the database
@software.each do |s|
csv << [s.amount, s.productcode, s.description, s.supplier]
end
end
send_data(software, :type => 'text/csv', :filename => 'software.csv')
end
find_by_sql(["SELECT s.supplier, s.productcode, s.description, CAST(SUM(l.amount) as UNSIGNED) AS amount