So i create a shortener url web application using Ruby on Rails with stimulus.
So when it goes to localhost:3000 it will goes to root url which will be handled by home_controller.rb method index and the view is like this below
<div class="px-4 py-5 my-5 text-center">
<%=image_tag("logo.svg", class: "d-block mx-auto mb-4", height: '57', width: '72')%>
<h1 class="display-5 fw-bold">MINIURL</h1>
<div class="col-lg-6 mx-auto">
<p class="lead mb-4">Your Alternative URL Shortener</p>
<div data-controller="home">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Place URL here" id="url-query" data-home-target="urlquery">
<button class="btn btn-primary" type="button" id="button-shorten" data-action="click->home#shorten">Shorten!</button>
</div>
</div>
</div>
</div>
it connect to home_controller.js
import { Controller } from "@hotwired/stimulus"
import { FetchRequest } from '@rails/request.js'
export default class extends Controller {
static targets = [ "urlquery" ]
connect(){
console.log("home controller connected!")
}
shorten(){
const urlQueryElement = this.urlqueryTarget
const urlQuery = urlQueryElement.value
const requestData = { og_url: urlQuery }
this.postShorten(requestData)
}
async postShorten (bodyRequest) {
try {
const request = new FetchRequest(
'post', '/mappings',
{ body: JSON.stringify(bodyRequest) }
)
await request.perform()
} catch (error) {
return error
}
}
}
what it does basically just send url from the input text to rails controller which is at /mappings via POST method.
Everything went well. data got saved. the POST request goes to mappings_controller.rb method create, this is my code
def create
original_url = mappings_param[:og_url]
rand_key = SecureRandom.alphanumeric(8)
mapping_url = Mapping.new(
og_url: original_url,
key: rand_key,
hit_count: 0
)
if mapping_url.valid?
# mapping_url.save!
render template: "mappings/show"
return
# render :json => {:short_url => "#{request.host}/#{mapping_url.key}"}
# redirect_to action: :show, id: "#{request.host}/#{mapping_url.key}"
# redirect_to root_path(:short_url => "#{request.host}/#{mapping_url.key}")
# respond_to do |format|
# format.js { render :js => "window.location='#{ root_path }'" , :locals => {:short_url => "#{request.host}/#{mapping_url.key}"}}
# end
# respond_to do |format|
# format.turbo_stream { redirect_to root_path(:short_url => "#{request.host}/#{mapping_url.key}") }
# end
else
head :bad_request
end
end
I want it to be redirect to root_path but with parameter shortened url. but it won't redirect. i already try several codes (you can see by code that i comment out). instead it just show text/html response if i see via console.
how can i redirect to root path with parameter after request post succeed and i want to put the shortened url in the input form. thanks
