Rails passing in params to association on create method I am currently using a belongs_to relationship in my Rails application to link a map and a group an object that way I can assign those maps to the user based on the group they are in. 

I have this mapgroup model.

class Mapgroup &lt; ApplicationRecord
  belongs_to :map, optional: true
  belongs_to :group, optional: true
end


I am getting the map from a dropdown menu in the form but I don't want a dropdown for the group because the use is already in that group. 

I opted to assign the group_id in the url to the mapgroup in the create method.

def create
  @mapgroup = Mapgroup.create(mapgroup_params)
  @mapgroup.group_id = params[:group_id] &lt;-- right here

  respond_to do |format|
    if @mapgroup.save
      format.html { redirect_to groups_path, notice: 'Mapgroup crated' }
    else
      format.html { render :new, notice: 'That shit failed' }
    end
  end
end


Is this a good practice? I have done this in previous apps but it seems a bit...smelly. Is there a more elegant way to do this?
You have two issues here:


need to find parent model first, and then build association (as group_id could be wrong)
create would try to save record, so you're trying to save twice. Use build/new instead.


    def create
      @group = Group.find(params[:group_id])
      @mapgroup = @group.mapgroups.build(mapgroup_params)

      respond_to do |format|
        if @mapgroup.save
          format.html { redirect_to groups_path, notice: 'Mapgroup crated' }
        else
          format.html { render :new, notice: 'That shit failed' }
        end
      end
    end