Rails link_to new with parameters not preserving parameters
So, I have two objects, Floor, which have _Many FloorMonsters, and FloorMonster, which are owned by floors.
I have link_to new_floor_monster_path in the show page on Floor, and I intend to pass the Floor id as a parameter. Link_to currently looks like this:
= link_to "Add a Monster to this Floor", new_floor_monster_path(floor_id: @floor.id)
In the FloorMonster controller, the new method is:
def new
@floor_monster = FloorMonster.new(floor_id: params[:floor_id])
respond_to do |format|
format.html # new.html.erb
format.json { render json: @floor_monster }
end
end
When I click on the link, the url shows the parameters:
http://.../floor_monsters/new?floor_id=4
But when I save, floor_id is zero and the program crashes. What am I missing here? I have tracked sources that do exactly what I did, but I am not getting any success. The accepted answer here and this blog post do exactly what I'm doing as far as I can tell, but managed to get it to work.
source to share
I am assuming that you are expanding the new FloorMonster on the form to allow other attributes to be set and then save it. To pass the attribute floor_id
along with the create action, you will need to add a field to it for your form. If you don't want to be seen or edited, use hidden_field
. In your form add:
= f.hidden_field :floor_id
source to share