I used "p current_user" in the controller to see if the jquery "get" is even getting to the appropriate action in the controller. It is not! Here's the code.
Relevant portion of jquery code used to send the array (note the path):
update: function(event, ui)
{
var sOrder = $(this).sortable('toArray');
$.get('<%= update_strength_order_s_order_index_path %>', {'sOrder[]':sOrder});
// i confirmed this route using rake routes
开发者_StackOverflow社区 }
The output to the console:
Started GET "/s_order/update_strength_order?sOrder%5B%5D=21&sOrder%5B%5D=7&sOrder%5B%5D=13&sOrder%5B%5D=12&sOrder%5B%5D=16&sOrder%5B%5D=9&sOrder%5B%5D=11&sOrder%5B%5D=18&sOrder%5B%5D=24&sOrder%5B%5D=8" for 127.0.0.1 at Sun Jun 05 01:47:29 -0400 2011
Route:
resources :s_order do
collection do
post :update_strength_order
end
end
Relevant rake routes result:
update_strength_order_s_order_index
Error msg in the console:
The action 'show' could not be found for SOrderController
I've just transitioned to using jQuery and am having trouble with the path thing. Since it was a jQuery get, but really a rails post, i tried both in the route and that didn't change the end result. I've Googed everything i can think of with no solution. Thanks!
You will need to get the param values. (I also am using each_with_index and just one find method). I am assuming that you have a fixed number of sOrders for each user.
def update_strength_order
sOrders = current_user.s_orders # In model: has_many :s_orders, :order => :position
[*params['sOrder']].each_with_index do |value, index|
str_order = index + 4 # starts with the fifth
sOrder[str_order].update_attributes(:strength_id => value) unless sOrder[str_order].nil?
end
render :nothing => true
end
Suggestion
I would put this logic in the model. It is better practice to have skinny controller and fat models.
Your controller would look something like...
def update_strength_order
current_user.reposition_strength_orders_to params['sOrder']
render :nothing => true
end
while the user model...
def User
has_many :s_orders, :order => :position
def reposition_strength_orders_to(sorder_ids=[])
[*sorder_ids].each_with_index do |value, index|
str_order = index + 4 # starts with the fifth
if s_orders[str_order].nil?
#create a new s_order
else
s_orders[str_order].update_attributes(:strength_id => value)
end
end
end
end
You'll have to parse it out by hand
Something like:
vars = request.query_string.split("&")
sOrder = vars.map{|var| var.split("=")[1]}
EDIT
Okay forget what I said groan.
Just modify your JS to look like:
$.get('/test', {'x[]': [567,233,678]});
// in your case
$.get('<%= update_strength_order_s_order_index_path %>', {'sOrder[]':sOrder});
Not sure what's up with that path either update_strength_order_s_order_index_path
so make sure that's correct too.
精彩评论