Say i have a GETrequest action called thankyou that redirects the user to the thankyou template after they have ordered and paid for an item. In said action, is it bad practice, since it's a GET request for me to update some attribute on the order?
e.g.
def thankyou
#order.update_attributes(:approval_required => true)
end
Related
I'm a newbie in RoR, trying to do the "Pragmatic Agile Web Development" depot application.
The application needs to keep track of all the items added to the cart by the buyer.
Here is the creation of the Cart model:
rails generate scaffold cart
And this is the application controller code:
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
end
My questions:
In the "scaffold" command I didn't specify any column name for this table, but still the Cart seems to have one column called "id". Is the scaffold command auto generate an "id" column?
In this rescue block, a new Cart object is created without setting any value to "Card.id". on the next line we assign this "id" value to "session[:cart_id] = cart.id". what is the value that will be stored?
Your answers will be appreciated,
Thanks
Answer of 1: Yes id is the autoincremented id column generated automatically by the scaffold generator. Each time a new entry will be created a new id will be generated.
Answer of 2: Yes a new object of Cart is created unless it can find one by the already stored cart_id in session. Hence after creating a new Cart, it saves the new cart_id in session for future uses. Like on next request when the controller will again call current_cart function, it will get a valid cart_id from session and the corresponding Cart object as well.
If you are not really aware of session or how sessions are handled in ROR, then you can follow these links.
Concept of Session
http://en.wikipedia.org/wiki/Session_(computer_science)
http://php.about.com/od/learnphp/qt/session_cookie.htm
Session In ROR
http://guides.rubyonrails.org/security.html
Let me know anything left confusing.
I was wondering what the best implementation for displaying a warning for a particular field being sent to the database.
To give you an example, somebody provides data which is considered valid, but questionable. So we want to treat it as if it was a regular validation error on the first go and confirm that it's what the user actually wants to enter. At this point they will have the option to either continue or change the data being entered. If they choose to continue they'll be given the go-ahead and we'll skip that validation on the next run-through.
However (and this is the part I'm not sure about), if they change that field to another value that can be considered questionable we want to take them through the same process. Keep in mind these are new records and not records that have already been persisted to the database.
Can such a feat be accomplished with basic conditional validations? Would there be a better option?
Just to clarify my application knows exactly how to handle this questionable data, but it's going to be processed differently than normal data and we just want to inform the user ahead of time with a warning.
Currently the validation is your typical custom validation method that dictates the validity of an object.
validate :some_field_some_rules
def some_field_some_rules
if some_conditions_must_be_true
errors.add(:some_field, "warning message")
end
end
Edited, let's try with a custom validation that will be triggered only when you need to.
class MyModel < ActiveRecord::Base
attr_accessor :check_questionable
validate :questionable_values_validation, on: :create, if: Proc.new { |m| m.check_questionable }
def initialize
check_questionable = true
end
private
def questionable_values_validation
if attribute1 == "Questionable value"
self.errors[:base] << "Attribute1 is questionable"
check_questionable = false
end
end
end
Then, when you render the create form, be sure to add an hidden_field for check_questionable :
f.hidden_field :check_questionable
So the first time, when calling the create action, it'll save with check_questionable = true. If there's a questionable value, we add an error to ActiveRecord standard errors AND set the check_questionable to false. You'll then be re-rendering the new action but this time with the hidden_field set to false.
This way, when the form is re-submitted, it won't trigger questionable_values_validation ...
I didn't test it, might need some tweak, but it's a good start I believe!
I have a Rails application where user parameters are all provided via a RESTful API with JSON parameters. Specifically, there is no client-side HTML form from which the user posts data: it's raw JSON.
So to create a new Car entry, the user might:
POST www.mysite.com/api/car
model=Ford&year=2012
In my app, by the time I receive this, the Action Pack values are intermingled with the user values in the params[] hash, so I get:
params = {:model=>"Ford", :year=>"2012", :format=>"json", :action=>"create", :controller=>"api/cars"}
What's the best way to separate the user-generated parameters from parameters generated by Action Pack? The best I can think of is to delete the latter:
car_params = params.reject {|k,v| [:format, :action, :controller].member?(k)}
car = car.new(car_params)
but that doesn't smell right. Is there a better way? (For example, can I get Action Pack to encapsulate the user supplied params into a single hash and pass that as a single element of params[]?)
Don't know if it can help, but I'd just create a method in application_controller :
def user_params
return params.reject {|k,v| [:format, :action, :controller].member?(k)}
end
So throughout the code, you can just use user_params when you don't want ActionPack params
I'm building a web service app and I'm trying to handle nicely a 422 page sending back to the user the JSON the POSTed to better debug the error. To do this, I use request.request_parameters which get me back the JSON I sent, but it happens to be organized (for me) in a wired way and I can't really get it back only with the original data
What I send as JSON is this.
{
"name":"New set intensity",
"properties":
[
{"uri":null,"value":"on"},
{"uri":"https://type.lelylan.com/properties/intensity","value":"100.0"}
]
}
What I get from request.request_parameters is this.
{"{\"name\":\"New set intensity\",\"properties\":"=>{"{\"uri\":null,\"value\":\"on\"}, {\"uri\":\"https://type.lelylan.com/properties/intensity\",\"value\":\"100.0\"}"=>{"}"=>nil}}}
My main problem is that somehow the content becomes the key, and this recursively inside. Is there a way to get back the clean data? Thanks a lot.
UPDATE: I'm trying to better understand where and why this problem occurs.
In my controller I tried to access in the two available ways I know.
#Â request.body.read.inspect
"{\"name\":\"New set intensity\",\"properties\":[{\"uri\":\"not_valid\"}]}"
# request.request_parameters
{"{\"name\":\"New set intensity\",\"properties\":"=>{"{\"uri\":\"not_valid\"}"=>{"}"=>nil}}}
The request is made from Capybara
page.driver.post(#uri, #params.to_json)
The controller returns only JSON so this is the way I defined it. I din't put 'respond_to' and 'respond_with' and when I make the request it renders the json view show.rabl.json. This makes me think that it recognize the correct format.
class FunctionsController < ApplicationController
before_filter
...
def index
...
end
def show
..
end
def create
body = JSON.parse(request.body.read)
#function = Function.new(body)
if #function.save
render 'show', status: 201, location: FunctionDecorator.decorate(#function).uri
else
render_422 "notifications.resource.not_valid", #function.errors
end
end
Thanks.
In my Rails App, there's home_controller.rb, in which I'd like to use un-related table(User model).
When I access example.com/home/index, I'd like it to send message to 4th id person in User table.
I'm using mailboxer gem to send message.
I added these to home_controller.rb
class HomeController < ApplicationController
def index
receipt = User.find(4)
receipt.send_message(receipt, "Body2", "subject2")
end
end
in home model, it's totally empty.
It certainly sends message. But it sends to 1st id person, who is current user.
How can I fix this?
Sounds like the send_message method delivers email to the object that receives the method call, not the object in the first argument. Try calling
receipt.send_message(receipt, "Body", "subject")