问题
I use Ruby on Rails 3 and I have 2 applications (APP1 and APP2) working on two subdomains:
- app1.domain.local
- app2.domain.local
and I am tryng to run two consecutive HTTP GET requests from APP1 to APP2 like this:
Code in APP1 (request):
before_filter :run_request
def run_request
response1 = Net::HTTP.get( URI.parse("http://app2.domain.local?test=first&id=1") )
response2 = Net::HTTP.get( URI.parse("http://app2.domain.local/test=second&id=1") )
end
Code in APP2 (response):
before_filter :run_response
def run_response
respond_to do |format|
if <model_name>.find(params[:id]).<field_name> == "first"
<model_name>.find(params[:id]).update_attribute ( <field_name>, <field_value> )
format.xml { render :xml => <model_name>.find(params[:id]).<field_name> }
elsif <model_name>.find(params[:id]).<field_name> == "second"
format.xml { render :xml => <model_name>.find(params[:id]).<field_name> }
end
end
end
After the first request I get the correct XML (response1 is what I expect), but on the second it isn't (response2 isn't what I expect). Doing some tests I found that the second time that <model_name>.find(params[:id]).<field_name>
run (for the elsif statements) it returns always a blank value so that the code in the elseif statement is never run.
Is it possible that the problem is related on caching <model_name>.find(params[:id]).<field_name>
?
NOTICE
If I try this code
respond_to do |format|
if <model_name>.find(params[:id]).<field_name> == "first"
<model_name>.find(params[:id]).update_attribute ( <field_name>, <field_value> )
format.xml { render :xml => <model_name>.find(params[:id]).<field_name> }
else
format.xml { render :xml => <model_name>.find(params[:id]) }
end
end
the response2 is the whole <model_name>.find(params[:id]
object. Note that I removed the "elsif" condition (in order to run the second request, so that I can get response2) and I changed the code from
format.xml { render :xml => <model_name>.find(params[:id]) }
to
format.xml { render :xml => <model_name>.find(params[:id]).<field_name> }
P.S.: I read about eTag and Conditional GET, but I am not sure that I must use that approach. I would like to keep all simple.
回答1:
It is possible the query is cached at the application controller level. Rails destroys query caches at the end of actions, but your queries are not in an action.
For what it's worth the code in APP2 most likely shouldn't be in the application controller, but in an action in the controller. That is much more RESTful, and will probably also take care of caching issues (as Rails will clear the query cache between APP1's requests).
来源:https://stackoverflow.com/questions/4636704/cache-problem-running-two-consecutive-http-get-requests-from-an-app1-to-an-app2