I have a query in my code as below
@sqladdpayment = "INSERT INTO payment开发者_如何学编程s (orderid, ttlprodcost, paytype,
paystatus,created_at,updated_at,userid,storeid)
VALUES ('" + session[:ordersid] + "', '" + session[:totalcost] + "', '"
+ "1"+ "', '" + "complete" +"',current_date, current_date, '"+"1"+"','"+ "1"+"')"
Here the table payments
and primary key is orderid
. Now, I know if I convert this to the ActiveRecord
way then I will not have to put update_date
, current_date
because it will put that on it's own. It will also put orderid
on it's own also (auto_increment
).
I am looking for a way to convert the above query to ActiveRecord
Rails way but still be able to put orderid
on my own (session[:ordersid]
). I do not want to rely on auto_increment
because then I will have to refactor lot of the other code. This might be a quick and dirty fix but I want to know whether this type of flexibility is offered in rails?
I have wondered about this question many times. Why won't rails allow me to have that flexibility?
You seem to go to a lot of trouble, or maybe i am missing something. The ActiveRecord way of doing thing is, imho either manually
payment = Payments.new
payment.orderid = session[:ordersid]
payment.totalcost = session[:totalcost]
payment.paytype = 1
payment.paystatus = "complete"
payment.userid = 1
payment.storeid = 1
payment.save
Now, if you have a form filling up these fields, it is even easier:
payment = Payment.new(params[:payment])
payment.save
So there is no need for an autoincrement field. If you specified that `ordersid' is the id, you can still set the value manually, which will overrule the rails standard behaviour (unless you defined the field to be autoincrement inside the database).
For instance: an article showing how to use uuids instead of autoincrement.
I do have a remark, when i see this code. Normally for userid
and storeid
one would use the inherent relational capabilities built into rails.
For instance, if a payment is related to a user, you either do
user.payments.build(params[:payment])
and then the newly created payment is automatically linked to the user. Or
payment.user = current_user
if you would have something like
belongs_to :user
in your model. Maybe you are aware of all that already, that is hard to make up from your question.
精彩评论