So, I have two objects, Floor, which has_many FloorMonsters, and FloorMonster which belongs_to Floor.
I have a link_to new_floor_monster_path in the show page on Floor, and I intend to pass the Floor id as a parameter. The link_to currently looks like this:
= link_to "Add a Monster to this Floor", new_floor_monster_path(floor_id: @floor.id)
In the controller for FloorMonster, the new method is this:
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 the link, the URL shows the parameters:
http://.../floor_monsters/new?floor_id=4
But when I save, the floor_id is nil and the program crashes. What am I missing here? I've tracked down sources that do exactly what I did, but I am getting no succes. The accepted answer here and this blog post are doing exactly what I am doing as far as I can tell, but they managed to get it to work.
I assume that you are exposing the new FloorMonster in a form to allow setting other attributes and then saving it. In order to pass the floor_id
attribute along to the create action, you will need to add a field to your form for it. If you don't want it to be seen or to be editable, use a hidden_field
. In your form, add:
= f.hidden_field :floor_id