Newbie on Ruby here, I've successfully build an html form in which users' "project" models can "follow" (or as I've phrased it "pfollow") other "plant" models. The only problem is that the code I've built doesn't work when users try to "pfollow" multiple plants on one form, which forces the user to hit "submit" multiple times for more plants. If the user selects more than one plant from a selection box at a time, my "project" model and my "prelationship" controller choke on the input, which comes as an array rather than the expected single integer (aka, the "pfollower_id" from the plant which is used by the "prelationships" controller for its create action).
How can I teach my app to accept an array of "pfollower_id(s)" and then create multiple plant prelationships?
Here is the error:
undefined method `id' for #<Array:0x26abe70>
app/models/project.rb:35:in `pfollow!'
app/controllers/prelationships_controller.rb:6:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"NKqa1f0M2yPLQDHbRLnxl3SiwBeTus/1q1hpZjD7hgY=",
"prelationship"=>{"pfollower_id"=>["4",
"5"]},
"project_id"=>"90",
"commit"=>"Pfollow"}
My "prelationships" controller:
class PrelationshipsController < ApplicationController
def create
@project = Project.find(params[:project_id])
@plant = Plant.find(params[:prelationship][:pfollower_id])
@project.pfollow!(@plant)
respond_to do |format|
format.html { redirect_to @project }
format.js
end
end
end
And the suspect "pfollow!" method in my model that the trace indicates is also culpable:
def pfollow!(pfollowed)
prelationships.create!(:pfollowed_id => pfollowed.id)
end
The form works fine, so it's just this controller and method that can't handle an array of pfollower_ids.
I'm desperate for help! Any and all direction would be immensely helpful.
Break it down with an each
method in your controller :D
params[:prelationship][:pfollower_id].each do |p|
@project.pfollow!( Plant.find(p) )
end
I'm guessing this would work if only one param is returned as well. Not entirely sure.