Further to the comment from Ankush Kataria, the form_for
helper basically creates a form which combines all the params into a hash, as opposed to form_tag
, which just makes the params independently
As you've discovered, this means your params will be accessed by:
#form_for
params[:variable][:param]
#form_tag
params[:param]
form_for
The reason why this is important is because if you're using the RESTful
routes interface, you'll be able to create
/ edit
/ update
a variety of records
form_for
basically keeps consistency throughout this process, pre-populating your forms with the various values, and keeping your code DRY
To call a form_for
helper, you have to define the @varaible
the form will populate. This @variable
needs to be an ActiveRecord
object, and is why you have to build it in the new
action before your form shows
form_tag
form_tag
is much more independent of the form_for
helper, doesn't require any @variable
, and creates the params individually
You'd use a form_tag
for the likes of a contact us
form or similar
Your Code
Your form looks good, but your create
action can be dried up:
def create
@places = Place.all
@event = Event.new(event_params)
respond_to do |format|
if @event.save
format.html { redirect_to @event, notice: 'Event was successfully created.' }
format.json { render action: 'show', status: :created, location: @event }
else
format.html { render action: 'new' }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
private
def event_params
params.require(:event).permit(:title, :content).merge(user_id: current_user.id, place_id: params[:event][:place_id])
end