mbajur
mbajur

Reputation: 4474

Add user_id to nested_attributes with strong params

Can anyone please advice me on what's a best practive on adding user_id to nested models on parent model create/update ?

Let's say i have a Band model with many Song models assigned. Any user can edit a Band info and add any Songs using fields_for method in a view. Songs table has a user_id column, which should be populated with current_user.id.

I'm trying to figure out how to handle that in my BandsController using strong parameters but without any luck.

BandsController band_params method look more or less like that:

def band_params
  params.require(:band).permit(
    :name, :location, :city, :country_name, :country_code,
    songs_attributes: [:id, :name, :duration, :_destroy]
  )
end

I can hack that method and iterate through each songs_attributes element adding user id but isn't there any better / more secure / build-in functionality for such operation? If not, what's the most sufficient way?

Thanks in advance.

Upvotes: 1

Views: 345

Answers (2)

house9
house9

Reputation: 20614

I wrote a gem that will set created_by_id and updated_by_id automatically during save - https://github.com/house9/clerk

if you are using rails 4 you must install using git

Upvotes: 0

Philip7899
Philip7899

Reputation: 4677

Assuming your band already exists before a song is added:

def update
    @band = Band.find(params[:id])
    @band.user = current_user
    @band.update_attributes(band_params)      
end

If you create the band and song at the same time:

def create
    @band = Band.new(band_params)
    @band.user = current_user
    @band.save      
end

Upvotes: 1

Related Questions