Reputation: 7708
I'm trying to do a post request with uses multiple values for same name, html is similar to:
<input name="opt[]" value="1"/>
<input name="opt[]" value="2"/>
<input name="opt[]" value="3"/>
With mechanize I'm doing something like:
params = {'opt[]' => [1,2,3]}
agent.post 'url', params
With no luck.
I've tried with other options like opt: [1,2,3]
with no luck either.
Upvotes: 1
Views: 511
Reputation: 29308
According to the Documentation for Mechanize and the discussion in this GitHub Issue the proper way to submit these parameters is by using a 2D Array as follows
params = [["opt[]",1],["opt[]",2],["opt[]",3]]
agent.post 'url', params
While reading the GitHub concern it appears that this is a known functional constraint and that they are or are planning on making efforts to resolve this but for the time being this is the proper method of submission. If you would prefer to use a Hash
structure manipulation would not be that difficult e.g.
def process_to_mechanize_params(h)
h.map do |k,v|
if v.is_a?(Array)
v.map {|e| ["#{k}[]",e]}
else
[[k.to_s,v]]
end
end.flatten(1)
end
Then you can use
params = {'opt' => [1,2,3],'value' => 22, another_value: 'here'}
process_to_mechanize_params(params)
#=>=> [["opt[]", 1], ["opt[]", 2], ["opt[]", 3], ["value", 22], ["another_value", "here"]]
Hope this helps. As @pguardiario pointed out a String would also be acceptable but I feel it might diminish readability.
Upvotes: 2
Reputation: 54984
You should be able to post them as a string:
agent.post url, 'opt[]=1&opt[]=2&opt[]=3'
Upvotes: 0