On my site I want a form to be rendered based on what type of data the user is inputing. When I call the controller method in my view, it's outputting tons of HTML where the form should be as plain text starting from DOCTYPE to . I'm using a post form that was previous in place statically to try it out.
Controller:
def feed_form(form_type)
form_type = %w{type_1 type_2}.include?(form_type) ? form_type : 'post'
render "_#{form_type}_form"
end
And the view calling the action:
= feed_form 'post'
And the form:
.feed-form
%h3 News Feed
= form_for(#post) do |f|
= render 'shared/error_messages', object: f.object
.field
= f.text_area :content, placeholder: "Make your new post here..."
= f.submit "Post", class: "post-button"
You are don't supposed to call controller methods from a view.
You must prepare all the data for view rendering (e.g. all required models) in controller method, and put it into #variables.
And then in view you write all your html using already prepared #variables, you can call helpers methods from a view, but not controller's.
Try to put your def feed_form(form_type) code into a helper.
P.S.: and read something about MVC architecture.
Related
I have a select form which determines which values are shown in a table. The values are stored in a json file. My Question is: what is the best way to do this cuz i have a gut feeling smth might be wrong with my solution.
Im able to open the json file and save it in a json/jbuilder object in my controller and then call the object in my view and pass the json in the select which calls a stimulus function, which then handles what is shown on the table.
Main Controller:
class MainController < ApplicationController
def index
#itemsJSON = JSON.parse(File.read('db/data.json'))
end
end
Index View
<%= form_with do |form| %>
<%= form.select :city, [['all'], ['critical'],['error'],['warning'],['info'],['debug']],
{ prompt: "Select Item Type" },
data: { controller: "dropdownTable", value: #itemsJSON,
action: "change >dropdownTable#selectData"} %>
<% end %>
Stimulus Function
Code that doesnt work gives back error: localhost:8080/main/db/database.json not found which // i dont understand why
//fetch('/db/data.json')
// .then((response) => response.json())
// .then((json) => console.log(json));
export default class extends Controller {
selectData(event){
... code that works
}
}
I'm building a practice Web API with Ruby + Sinatra and I want my responses to be displayed in a ERB template with formatted JSON (GeoJSON). So far I've been able to process the request and format the response correctly.
However, I can't find a way to display the contents in the endpoint as a JSON string, and it displays as a regular string (difficult to read for JSON). Is there any way to do that in Ruby + Sinatra without using JavaScript?
Here's what I've got so far in both files.
# app.rb
before do
json = File.open("data/cities.json").read
data = JSON.parse(json)
data.each do |item|
geoarray["features"].append(json_to_geojson(item))
end
#geojson = geoarray.to_json
end
...
get('/myendpoint') do
#activities = #geojson
erb :cities
end
<!--cities.erb-->
<%= #activities %>
try <%= #activities.to_json.html_safe %>
You can make JSON string look prettier by using JSON.pretty_generate() method.
# app.rb
before do
json = File.open("data/cities.json").read
data = JSON.parse(json)
data.each do |item|
geoarray["features"].append(json_to_geojson(item))
end
# use pretty_generate instead of to_json
#geojson = JSON.pretty_generate(geoarray)
end
And In your erb file. Instead of simple showing it, add <pre> tag to it.
<!--cities.erb-->
<pre><%= #activities %></pre>
reference
Rails drive me crazy. I'm trying to respond to with an action with JSON.
My goal is to let be the JSON the only format for a response to a URL.
Let's see some code.
The Model is a Devise user, with some added field.
The Controller is my UsersController that has this action
# /app/controllers/users_controller.rb
def static
render json: current_user
end
I got also this jbuilder view
# /app/views/users/static.json.jbuilder
json.content format_content(#user.content)
json.author do
json.name #user.name
json.email_address #user.email
end
if current_user.admin?
json.someValue "foo"
end
this View doesn't do some interesting stuff, but It's just a try.
Anyway I'll never get the static.json.jbuildercontent. I always get all Devise user's content as a JSON.
Am I doing something wrong? (or better: where I done the epic fail?)
Anyway found the solution:
# /config/route.rb
get 'my-static-json' => 'mycontroller#static', defaults: {format: :json}
# /app/controllers/mycontrollers_controller.rb
def my-static-json
end
# /app/views/mycontrollers/my-static-json.json.jbuolder
json.content "some static content"
this is only an example but gives have all the information that I needed
I would like to use link_to to call a controller action named show. This happens, I get a 200 message. Now I want to update a div with the content that is being returned.
Code in controller:
respond_to do |format|
format.html # show.html.erb
format.js
end
Code in view, link and JavaScript:
<%= link_to "Show analysis", company_comparison_path(3), :remote => true , :id => "thelink" %>
<div id="replaced"> will be replaced </div>
<script>
$('#thelink').bind('ajax:complete', function() {
$('#replaced').html(data)
});
</script>
I think I still don't understand how to return the HTML or JavaScript from the controller properly into the JavaScript. If I replace the word "data" in the JavaScript with some text in brackets, I get proper output. But how do I get the result from the controller action?
You were almost there, but you need to tell the bound function what the actual html content is you want to insert into your #results div. When you call .html() on $('#replaced') the variable you use (data) is still undefined.
Try the following:
$('#thelink').bind('ajax:complete', function(event, data) {
$('#replaced').html(data.responseText);
});
edit: Oh, something to keep in mind is that this may render your view including the layout which is probably not what you want. You can add something like render layout: false if request.xhr? to your controller to prevent the layout from showing up on ajax requests.
If you want to return richer content from the AJAX response, you can render the view from the controller by the :render_to_string method.
See more: http://apidock.com/rails/ActionController/Base/render_to_string
respond_to do |format|
format.html # show.html.erb
format.js {
#content = render_to_string(:partial => 'some_partial_view')
}
end
I have two files. .rb (with Ruby code) and .erb(HTML file with some ruby script). I am calling a Ruby function in .rb from .erb.
.erb
Click here
.rb
def showProducts(param)
//Some code
end
I am able to call a function without passing parameters to it. But as and when I pass parameters to function and then call it, I receive an error. I know this is the incorrect way to call a parametrized function from .erb. What is the correct way of calling a parameterized function from HTML?
If you add in another key/value pair to the hash in url_for
<%= url_for :action => :showProducts, :product => "toaster" %>
Your URL should go from, say, http://localhost:3000/showProducts to http://localhost:3000/showProducts?product=toaster
Here, we're adding parameters to the GET request. To access these parameters in the controller we use the params hash. For example to get the product (toaster):
params[:product] #=> "toaster"
I found the solution to my problem :
<a href="<%= url_for :action => :showProducts, :id=> 'Hello' %>">
.rb function:
def showProducts(param)
//Some code
end
I found the solution
def showProducts
#params['product']
end