amr
amr

Reputation: 1275

Rails form params issue

I'm constructing some data to send over jQuery's $.post, the data that I send looks like this:

authenticity_token: LxHlgi1WU8o0DtaNuiQOit/e+HlGR2plVcToHUAhA6I=
crews[0][boat_id]: 2
crews[0][crew][]: 10
end_time: 1280408400
start_time: 1280404800

Which is from jQuery converting the data object which is prepared by:

Then in my controller I have:

def create
  @outing = Outing.create(
    :club => current_user.club,
    :title => 'Outing',
    :start_time => Time.at(params[:start_time].to_i),
    :end_time => Time.at(params[:end_time].to_i)
  )
  @outing.save

  Rails.logger.debug(params[:crews].inspect)
  params[:crews].each_with_index do |crew,i|
    Rails.logger.debug(crew.inspect)

    @crew = Crew.create(
      :boat_id => crew[:boat_id].to_i,
      :outing_id => @outing.id
    )
    @crew.save

    crew[:crew].each do |c|
      @cu = CrewUsers.create(
        :crew_id => @crew.id,
        :user_id => c.to_i
      )
    end
  end

  render :nothing => true    
end

The two inspect statements print something like this:

{"0"=>{"crew"=>["10"], "boat_id"=>"2"}}
["0", {"crew"=>["10"], "boat_id"=>"2"}]

and I get this error:

TypeError (Symbol as array index):

To me, crews shouldn't be an indexed array, and that's where the issue is. But I could also be totally wrong. Any ideas on what I'm doing wrong or how to fix it?

Upvotes: 0

Views: 668

Answers (1)

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94274

Your params[:crews] is a Hash, but you're trying to use it as if it's an Array. Hashes don't have indexes, per se, but rather keys.

You could get the result you're looking for if you use Hash#each_pair (or Hash#each_value if you don't need keys) instead of each_with_index:

params[:crews].each_pair do |i, crew| # note that the block parameters are reversed
  ...
end

To demonstrate:

hash = {"0"=>{"crew"=>["10"], "boat_id"=>"2"}}
hash.each_pair do |i, crew|
  puts crew.inspect
end
#=> {"crew"=>["10"], "boat_id"=>"2"}

Note that you will still have an issue looking for crew[:boat_id], because your keys are strings and not symbols.

Upvotes: 2

Related Questions