我需要能够输出由Rails生成的SQL UPDATES,而不是实际运行它们或保存记录。我将把SQL更新输出到文件中。
有没有办法在Rails中执行此操作,而不使用字符串插值?
是否可以执行以下操作:
<div id="container">
<h1>BMI and Blood Pressure Calculator</h1>
<div id="body">
<p>This webpage allows users to calculate their BMI and Blood Pressure by entering in their values into the boxes</p>
</br>
<p>Please enter in your details below</p>
<form>
<br />
<br />Patient Information
<br />Height <input type="text" name="height" size="12" maxlength="20">
<br />Weight <input type="text" name="weight" size="12" maxlength="20">
<br />
<br /><input type="reset" value="Clear Form">
<br /><input type="submit" value="Submit Information">
</form>
</div>
<?php
$this->input->post('height');
$this->input->post('weight');
if ($_GET['submit']) {
$height = $_GET['height'];
$weight = $_GET['weight'];
}
function bmi($height,$weight) {
$bmi = $weight/($height*$height);
return $bmi;
}
$bmi = bmi($weight,$height);
if ($bmi <= 15) {
$output = "Very severely underweight";
} else if ($bmi > 15 AND $bmi<=16 ) {
$output = "Severely underweight";
} else if ($bmi > 16 AND $bmi<=18.5) {
$output = "Underweight";
} else if ($bmi > 18.5 AND $bmi<=25) {
$output = "Normal";
} else if ($bmi > 25 AND $bmi<=30) {
$output = "Overweight";
} else if ($bmi > 30 AND $bmi<=35) {
$output = "Obesity class 1";
} else if ($bmi > 35 AND $num<=40) {
$output = "Obesity class 2";
} else if ($bmi > 60) {
$output = "Obesity class 3";
echo "Your BMI is " . $bmi . " and you are : ";
echo "$output";
}
?>
而不是:
p = Post.where (something)
p.some_value = some_new_value
p.to_sql??? # how to generate the update statement
答案 0 :(得分:2)
从@ R.F开始。尼尔森并将其包装成一种方法。您可以使用模型调用to_update_sql
作为获取SQL的参数。
def to_update_sql(model)
return '' if model.changes.empty?
table = Arel::Table.new(model.class.table_name)
update_manager = Arel::UpdateManager.new(model.class)
update_manager.set(model.changes.map{|name, (_, val)| [table[name], val] })
.where(table[:id].eq(model.id))
.table(table)
return update_manager.to_sql
end
post = Post.first
post.some_value = xxxx
to_update_sql(post)
# => UPDATE `posts` SET `some_value` = xxx WHERE `posts`.`id` = 1