I'm trying to render HTML from an ERB object within a controller (the ERB object is stored in the DB), but with no success.
I would like to do something like this:
First, I created a Func instance:
Func.Create(text: "<% #users.each do |user| %>
<td><%= user.id %></td>
<td><%= link_to user.username, user_path(user) %></td>")
Then, in the controlller:
class MainController < ApplicationController
def foo
#users = User.all
render :html => bar(binding)
end
def bar(controller_binding)
html = Func.find(1)
template = ERB.new(html.text)
template.result(controller_binding)
end
end
But all I get are errors, like this:
"Missing template main/resource_name, application/resource_name with
{:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby,
:jbuilder, :coffee]}. Searched in: * "c:/Users/david/sample/app/views""
and
"(erb):3: syntax error, unexpected $end, expecting keyword_end ...
ut.force_encoding(__ENCODING__) ... ^"
Replace
Func.Create(text: "<% #users.each do |user| %>
<td><%= user.id %></td>
<td><%= link_to user.username, user_path(user) %></td>")
with
Func.Create(text: "<% if #users.nil? %>
<p> There are no users in database </p>
<% else %>
<% #users.each do |user| %>
<td><%= user.id %></td>
<td><%= link_to user.username, user_path(user) %></td><% end %> <% end %>")
<% end %> end of block was missing.
Also, replace render :html => bar(binding) with render :inline => bar(binding)
You could also shorten your code as below,
def foo
#users = User.all
html = Func.find(1)
render :inline => html.text
end
You shouldn't doing that in the controller. Not sure what you're trying to accomplish but it looks like a helper may be more appropriate.
Related
I am trying to recover the error message of the validations on my form (there must be no duplicate of ingredient) but I always have a MISSING TEMPLATE that I can not correct, I know that It's a routes problem, but I do not know which one.
I have 3 models, Cocktail Ingrédient and Dose, Dose link Cocktail and Ingredient
ERROR MESSAGE
MISSING TEMPLATE
Missing template cocktails/23 with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in: * "/home/dezrt/code/Pseud0/rails-mister-cocktail/app/views"
doses_controller.rb
class DosesController < ApplicationController
before_action :set_dose, only: [:show, :destroy, :edit]
def index
#doses = Dose.all
end
def show
end
def new
#dose = Dose.new
end
def create
#dose = Dose.create(dose_params)
#cocktail = Cocktail.find(params[:cocktail_id].to_i)
#dose.cocktail = #cocktail
if #dose.save
redirect_to cocktail_path(#dose.cocktail)
else
# params[:dose][:cocktail_id] = #cocktail.id.to_s
#ingredient = Ingredient.find(params[:dose][:ingredient_id].to_i)
render cocktail_path(#cocktail)
end
end
def edit
end
def destroy
#dose.destroy
redirect_to cocktail_path(#dose.cocktail)
end
private
def dose_params
params.require(:dose).permit(:cocktail_id, :ingredient_id, :quantity, :description)
end
def set_dose
#dose = Dose.find(params[:id])
end
end
cocktails_contronller.rb
class CocktailsController < ApplicationController
before_action :set_cocktail, only: [:show]
def index
#cocktails = Cocktail.all
end
def show
#cocktail = Cocktail.find(params[:id])
#dose = Dose.new
#dose.cocktail = Cocktail.find(params[:id])
#ingredient = Ingredient.new
#ingredients = Ingredient.all
end
def new
#cocktail = Cocktail.new
end
def create
#cocktail = Cocktail.create(cocktail_params)
if #cocktail.save
redirect_to cocktail_path(#cocktail)
else
#cocktail = Cocktail.new(cocktail_params)
render :new
end
end
private
def cocktail_params
params.require(:cocktail).permit(:name)
end
def set_cocktail
#cocktail = Cocktail.find(params[:id])
end
end
views/cocktails/show.html.erb
<h1>Cocktail X</h1>
<h2>Voici la listes de tout nos cocktails</h2>
<div class="container">
<h3>Nom du cocktail : <%= #cocktail.name %></h3>
<ul>
<h4>Ingredients : <% #cocktail.doses.each do |dose| %></h4>
<li><%= dose.ingredient.name %> : (<%= dose.quantity %><%= dose.description %>)</li>
<%= link_to dose_path(dose), method: :delete do %>
<i class="fa fa-close"></i>
<% end %>
<% end %>
</ul>
</div>
<%= link_to "Retour aux cocktails", cocktails_path %>
<div class="container">
<h4>Ajouter des ingrédients</h4>
<%= simple_form_for [#cocktail, #dose] do |f| %>
<%= f.input :ingredient_id, collection: #ingredients %>
<%= f.input :quantity, label: 'Quantité', error: 'La quantitée est obligatoire' %>
<%= f.input :description, label: 'Description', error: 'La description est obligatoire' %>
<%= f.button :submit %>
<% end %>
</div>
routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root "cocktails#index"
resources :cocktails do
resources :doses, only: [:new, :create, :edit]
end
resources :doses, only: :destroy
end
rails routes
Prefix Verb URI Pattern Controller#Action
root GET / cocktails#index
cocktail_doses POST /cocktails/:cocktail_id/doses(.:format) doses#create
new_cocktail_dose GET /cocktails/:cocktail_id/doses/new(.:format) doses#new
edit_cocktail_dose GET /cocktails/:cocktail_id/doses/:id/edit(.:format) doses#edit
cocktails GET /cocktails(.:format) cocktails#index
POST /cocktails(.:format) cocktails#create
new_cocktail GET /cocktails/new(.:format) cocktails#new
edit_cocktail GET /cocktails/:id/edit(.:format) cocktails#edit
cocktail GET /cocktails/:id(.:format) cocktails#show
PATCH /cocktails/:id(.:format) cocktails#update
PUT /cocktails/:id(.:format) cocktails#update
DELETE /cocktails/:id(.:format) cocktails#destroy
dose DELETE /doses/:id(.:format) doses#destroy
Thanks you for your help !
Missing template cocktails/23 with {:locale=>[:en], :formats=>[:html],
:variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby,
:coffee, :jbuilder]}. Searched in: *
"/home/dezrt/code/Pseud0/rails-mister-cocktail/app/views"
This line render cocktail_path(#cocktail) is the reason for the error. render loads a view. So the input to the render normally should be name of the file, in your case show view of the cocktails. Changing it to render 'cocktails/show' should fix the error.
Also you seems to be confused between render and redirect_to. I suggest you to read render vs redirect
I'm trying to figure out what an error message means. I am using statesman gem for states. One of my states is called 'requested'.
state :requested, initial: :true
state :approved
state :rejected
state :removed
transition from: :requested, to: [ :approved, :rejected ]
transition from: :approved, to: [ :removed ]
I have an index, listing all the states that an object can transition to:
<% if policy(orgReq).approved? %>
<%= link_to "APPROVE", requested_organisation_request_path(orgReq), :class=>'btn btn-info', method: :put %>
<% end %>
<% if policy(orgReq).rejected? %>
<%= link_to "DECLINE", decline_organisation_request_path(orgReq), :class=>'btn btn-info', method: :put %>
<% end %>
<% if policy(orgReq).removed? %>
<%= link_to "REMOVE", removed_organisation_request_path(orgReq), :class=>'btn btn-info', method: :put %>
<% end %>
</td>
I have a controller action for each state:
def requested
# this is the initial state - there is nothing in the controller action
end
def approved
organisation_request = OrganisationRequest.find(params[:id])
authorize #organisation_request
if organisation_request.state_machine.in_state?(:requested)
flash[:notice] = "You've been added as a member. Welcome aboard."
format.html { redirect_to :index }
else
flash[:error] = "You're not able to manage this organisation's members"
redirect_to(profile_path(current_user.profile))
end
end
def removed
organisation_request = OrganisationRequest.find(params[:id])
authorize #organisation_request
if organisation_request.state_machine.in_state?(:approved)
flash[:notice] = "Removed from the organisation."
format.html { redirect_to :index }
else
flash[:error] = "You're not able to manage this organisation's members"
redirect_to(profile_path(current_user.profile))
end
end
I don't understand what the error message below means? It comes when I try to click a button on the index to change the state of the object from requested to approved (which is an allowed transition).
Does anyone know how to interpret this error message? Do I need to add something to the requested method in the controller?
ActionView::MissingTemplate at /organisation_requests/1/requested
Missing template organisation_requests/requested, application/requested with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml, :jbuilder]}. Searched in:
I am new to rails. Currently trying to pull from an api and store the value of each api request into a form for entry into my DB.
My page has a search bar at the top which pulls the form the api and returns the value of each result to the screen with a button prompting to add to the DB.
<ul>
<% #movies.each do |movie| %>
<li><%= movie['Title'] %> | <%= movie['Year'] %> |
<%= form_tag(movies_path, :method => "post") do %> <%=hidden_field :movie, :title, :value => movie["Title"] %> <%= hidden_field :movie, :year, :value => movie["Year"] %> <%= hidden_field :movie, :imdb_id, :value => movie['imdbID'] %> <%= submit_tag "Add Movie", :name => nil %> <% end %> </li><br>
<% end %>
</ul>
My controller for both my create a #movie for the index/ search results page is this
class MoviesController < ApplicationController
def index
if params[:search].present?
#movies = Omdbapi.search(params[:search])
else
render :'/watchlists'
end
end
def show
#movie = Omdbapi.more_info(params[:imdb_id])
end
def create
#movie = Movie.new(movie_params)
if #movie.save
redirect_to movies_path(#movie)
end
end
When I try to hit submit rails throw this error
Missing template movies/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.
Any help would be awesome.
#movie did not persisted for some reason so that redirect_to hasn't been performed. Add else statement to condition:
if #movie.save
redirect_to movies_path(#movie)
else
render action: 'new'
end
I am implementing ancestry on a nested resource.
resources :loads do
resources :messages
end
Here is my index action
def index
load = Load.find(params[:load_id])
#messages = load.messages.scoped
#message = load.messages.new
end
My index.html.erb is throwing the following error.
Missing partial messages/message with {:locale=>[:en],
:formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in:
* "C:/Sites/final/cloud/app/views"
My index.html.erb is as follow
<% title "Messages" %>
<%= nested_messages #messages.arrange(:order => :created_at) %>
<%= render "form" %>
Here is my nested_message definition
module MessagesHelper
def nested_messages(messages)
messages.map do |message, sub_messages|
render(message) + content_tag(:div, nested_messages(sub_messages), :class => "nested_messages")
end.join.html_safe
end
end
Here is my _message.html.erb
<div class="message">
<div class="created_at"><%= message.created_at.strftime("%B %d, %Y") %></div>
<div class="content">
<%= link_to message.content, message %>
</div>
<div class="actions">
<%= link_to "Reply", new_load_message_url(:parent_id => message) %> |
<%= link_to "Destroy", [message.load, message], :confirm => "Are you sure?", :method => :delete %>
</div>
</div>
Any help appreciated.
This error states that your application has tried to search for a partial _messages.html.erb, as a result of this the partial must not be in your /app/views/messages which results in the message you are being shown. Check your messages directory and check if you have this partial. Going by your nested resources I am guessing your association between Load and Message is:
class Load < ActiveRecord::Base
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :load
end
Further more I noticed that you have the following line in your index action: #message = load.messages.new surely this does not seem right. Because what your telling your application to do is when the controller recieves a response to render the index action it should also create message by doing #message = load.messages.new which is why it is trying to render the partial.
To clarify things a bit more for you. If in your application you had a link_to to create a new user. Upon clicking the new user it will do something like:
def new
#user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #user }
end
end
And will render `app/views/users/new.html.erb which inside this will most probably have a
<%= form_for #user do |f| %>
<%= render :partial => 'form', :locals => { :f => f } %>
<% end %>
This will call your partial which in normal cases would be _form.html.erb. The create action of a particular controller will come into play when you attempt to save the partial. Usually a create block for a controller will look like this:
def create
#title = "Create a user"
#user = User.new(params[:user])
if #user.save
redirect_to usermanagement_path
flash[:success] = "Created successfully."
else
#title = "Create a user"
render 'new'
end
end
Here inside the create action when your _form.html.erb or _message.html.erb is submitted it will try to create a new user by passing in the user through the params. I do thoroughly believe that your issue may potentially well be:
1) Your missing your _message.html.erb
2) Also you are calling a .new inside your index action.
Hope this clears this up for you.
I'm making a twitter-copy and right now I'm trying to show all the posts from the users an other user is following. I'm new at ruby and rails, so i might be doing this a really weird way..
These are the files I have:
session#home.html.erb
<h2 class='User_Header'> Home <h2>
<%= link_to "New Post", controller: "posts", action: "new" %>
<%= link_to "Log Out", :controller => "sessions", :action => "logout" %>
<%= show_tweets("following") %>
sessions_helper
module SessionsHelper
def show_tweets(opt)
if opt == "following"
#sub = Subscription.where("userID = ?", #current_user.id)
#post = Post.where("user_id = ?", #sub.followingID)
render partial: 'shared/follower_tweets'
end
end
def show_tweet(s)
#post = Post.where("user_id = ?", s.id)
render partial: 'shared/tweet'
end
def tweet_username(p)
#username = User.where("id = ?", p.user_id)
Rails.logger.debug #username.inspect
render partial: 'shared/user'
end
end
_follower_tweets.html.erb
<h2>Tweets</h2>
<table>
<tr>
<th>Username</th>
<th>Tweet</th>
</tr>
<% div_for(#post, class: 'post') do %>
<td><%= tweet_username(#post) %></td>
<td><%= #post.content %></td>
<% end %>
</table>
_user.html.erb
<%= #username %>
session.rb
class Session < ActiveRecord::Base
attr_accessible :content, :user_id, :followingID, :userID
end
Error
app/views/sessions/home.html.erb where line #9 raised:
undefined method `followingID' for #<ActiveRecord::Relation:0x007fd74b66f8a8>
What is happening is that you have followingID on your Session model instead of Subscription model. Should be something like the following:
class Subscription < ActiveRecord::Base
attr_accessible :followingID
end
However, the problem is bigger than that. You must read about Active Record Associations, then you would be able to do something like
#subs = #current_user.subscriptions
#posts = #current_user.posts
check if your model's association is correct. the messages indicates that there's an error about this.