I have a helper class that renders a partial to store the content in the database.
It works fine but when the view contains a url provided by the url helper
<%= link_to "Show project", projects_url, class: "button" %>
it throws the following exception
undefined local variable or method projects_url for #
The code to render in my helper named NotificationRender is
def render(options)
viewer = ActionView::Base.new()
viewer.view_paths = ActionController::Base.view_paths
viewer.extend ApplicationHelper
viewer.render options
end
I include this helper in a class Notification
class Notification < ActiveRecord::Base
include NotificationRender
.....
def self.create_for(user, event, params)
template = "notifications/_email_project"
list_params = {:template => template,:locals => params}
notification = Notification.new
notification.message = notification.render(list_params) #here I render the partial
notification.subject = I18n.t "subject.#{event}"
notification.to = user.email
notification.save
end
end
Related
I am pretty new to Ruby and I am working on a hangman game .
What I am trying to do is create a new game when the user simply click on a button and I want that "click" to redirect to the show of that game.
Here are my models :
class Game < ApplicationRecord
has_many :guesses
end
class Guess < ApplicationRecord
belongs_to :game
end
Here are my controllers :
class GamesController < ApplicationController
skip_before_action :authenticate_user!
def index
#games = Game.all
end
def create
#game = Game.new(game_params)
#game.save!
redirect_to game_path(#game)
end
def show
#game = Game.new
#game = Game.last
end
def destroy
#game = Game.find(params[:id])
#game.destroy
redirect_to home_path
end
private
words =[
"spokesperson", "firefighter", "headquarters", "confession", "difficulty", "attachment", "mechanical",
"accumulation", "hypothesis", "systematic", "attraction", "distribute", "dependence", "environment",
"jurisdiction", "demonstrator", "constitution", "constraint", "consumption", "presidency", "incredible",
"miscarriage", "foundation", "photography", "constituency", "experienced", "background", "obligation",
"diplomatic", "discrimination", "entertainment", "grandmother", "girlfriend", "conversation", "convulsion",
"constellation", "leadership", "insistence", "projection", "transparent", "researcher", "reasonable","continental",
"excavation", "opposition", "interactive", "pedestrian", "announcement", "charismatic", "strikebreaker",
"resolution", "professional", "commemorate", "disability", "collection", "cooperation", "embarrassment",
"contradiction", "unpleasant", "retirement", "conscience", "satisfaction", "acquaintance", "expression",
"difference", "unfortunate", "accountant", "information", "fastidious", "conglomerate", "shareholder",
"accessible", "advertising", "battlefield", "laboratory", "manufacturer", "acquisition", "operational",
"expenditure", "fashionable", "allocation", "complication", "censorship", "population", "withdrawal",
"sensitivity", "exaggerate", "transmission", "philosophy", "memorandum", "superintendent", "responsibility",
"extraterrestrial", "hypothesize", "ghostwriter", "representative", "rehabilitation", "disappointment",
"understanding", "supplementary", "preoccupation"
]
#word_to_guess = words.sample
#health_bar = 5
#game_status = "Game not started yet"
def game_params
params.require(:game).permit(#word_to_guess, #health_bar, #game_status)
end
end
Here is what I have been trying to do
<%= link_to "nouvelle partie", game_path(game), method: :create %>
but the errors message is :
"undefined local variable or method `game' for #ActionView::Base:0x0000000000d4d0"
POST method won't work with link_to. Try using the to button_to instead of link_to like this:
<%= button_to "nouvelle partie", game_path(game), method: :post %>
I think the bug is due to the variable game not being passed to partial. You have to pass it on like this:
<%= render "game", game: #game %>
And you don't have to pass variables in game_params. You only need to set them in the show method where you will be redirected from the create method. Also, you don't set the current game like this Game.last, you just take id which is contained in the url.
def create
#game = Game.new
#game.save!
redirect_to game_path(#game)
end
def show
#game = Game.find(params[:id])
#word_to_guess = words.sample
#health_bar = 5
#game_status = "Game not started yet"
end
have you tried?
<%= link_to "nouvelle partie", game_path(#game), method: :create %>
I have a controller which calls a class method from a model. However, I got undefined method 'where' for Jira:Class.
controller:
module Api
module V1
class JiraController < ApplicationController
def index
jira = Jira.where()
jira_stat = JiraStat.new(jira)
render json: [
{
t('jira.api.status') => jira_stat.status,
t('jira.api.number_of_jiras') => jira_stat.jira_total
}
]
end
end
end
end
model:
# frozen_string_literal: true
require 'active_model'
class Jira
include ActiveModel::Model
include JiraKit
attr_accessor :status, :jira
def self.where(status_name = 'all')
if status_name == 'all'
jiras = JiraKit.where.jira_issues(status: ['open', 'submitted', 'in
progress', 'in review', 'closed'])
elsif
jiras = JiraKit.where.jira_issues(status: [status_name])
end
new(#status = status_name, #jira = jiras)
end
end
I think I have used self keyword. But I don't know why I can't access that method. If I create an instance of Jira model, I am able to access that method.
I am testing one of my mailers using ActionMailer Preview and am using Struct to create my objects
class TransactionMailerPreview < ActionMailer::Preview
include Roadie::Rails::Automatic
def transaction_complete_mailer
orders = Struct.new(:image, :image_size, :mount, :frame, :frame_color)
transaction = Struct.new(:first_name, :email)
#transaction = transaction.new('Richard Lewis', 'test#gmail.com')
#orders = orders.new("Test Print Name", "10x8 Image Size", "10x8 Mount Size", "10x8 Frame Size", "White Frame")
TransactionMailer.transaction_complete_mailer(#transaction, #orders)
end
end
This is my actual mailer class
class TransactionMailer < ApplicationMailer
default from: ENV['EMAIL_ADDRESS']
def transaction_complete_mailer(transaction, orders)
#transaction = transaction
#orders = orders
attachments.inline['photography-logo-text.png'] = File.read(Rails.root.join('app', 'assets', 'images', 'photography-logo-text.png'))
mail(to: #transaction.email, subject: 'Your order from Glenn GB Photography') do |format|
format.html { render file: 'transaction_mailer/transaction_message.html.erb', layout: 'mailer' }
end
end
end
In my view I loop over the #orders as there could be multiple
transaction_message.htmnl.erb
<% #orders.each do |order| %>
<div class="order-summary">
<p><span class="bold">Print:</span><%= order.image %></p>
<p><span class="bold">Print Size:</span><%= order.image_size %></p>
<p><span class="bold">Mount:</span><%= order.mount %></p>
<p><span class="bold">Frame:</span><%= order.frame %></p>
<p><span class="bold">Frame Color:</span><%= order.frame_color %></p>
</div>
<% end %>
When I action this mailer in preview I get an error
undefined method `image' for "Test Print Name":String
I have two questions here
Why am I getting the error?
How would I create multiple order objects?
#orders is a singular object of type struct, but your your transaction_complete_mailer expects an array/collection named #orders. So when you call #orders.each do |order| in your Mailer, it's actually iterating through each key/value in the #orders struct object. This explains the error you're getting since "Test Print Name" is the first key declared in your Struct.
Wrapping your structs in an array should resolve the issue:
class TransactionMailerPreview < ActionMailer::Preview
include Roadie::Rails::Automatic
def transaction_complete_mailer
orders = Struct.new(:image, :image_size, :mount, :frame, :frame_color)
transaction = Struct.new(:first_name, :email)
#transaction = transaction.new('Richard Lewis', 'test#gmail.com')
#order = orders.new("Test Print Name", "10x8 Image Size", "10x8 Mount Size", "10x8 Frame Size", "White Frame") # Renamed to #order, since this is a single object
TransactionMailer.transaction_complete_mailer([#transaction], [#order])
end
end
I tried to run web server and it shows the following error:
undefined method `keys' for nil:NilClass error on rails
Extracted source (around line #21):
shopsList = [st1, st2, st3, st4]
render :json => shopsList
end
end
Here are the files:
shop.rb
class Shop < ActiveRecord::Base
attr_accessor :name, :description, :comments
def initialize(name, description, comments)
#name = name
#description = description
#comments = []
end
end
comment.rb
class Comment
attr_accessor :id, :name, :content
def initialize(id, name, content)
#id = id
#name = name
#content = content
end
end
shops_controller.rb
class ShopsController < ApplicationController
def index
end
def shops
com1 = Comment.new("FX991", "Goat", "Delicious!")
com2 = Comment.new("F2888", "Cow", "Amazing!")
com3 = Comment.new("GH555", "Cat", "Yummm!")
com4 = Comment.new("HY666", "Fish", "Mouth watering!")
commentList = [com1, com2, com3, com4]
sh1 = Shop.new("AAAA", "Je", commentList[0])
sh2 = Shop.new("NNNN", "Te", commentList[1])
sh3 = Shop.new("CCCC", "Be", commentList[1])
sh4 = Shop.new("DDDD", "He", commentList[1])
shopsList = [sh1, sh2, sh3, sh4]
render :json => shopsList
end
end
When I tried changing render :json => shopsList to render :json => commentList, the comment list would show as json format in the server.
Also, is there something wrong with the way I access or declare the commentList array? The contents of the array won't show when I try to access it. It just displays "[]"
You need to pass a hash to render
try this
shopsList = [sh1, sh2, sh3, sh4]
render :json => {:success=>true, :data=>shopsList}
Can you please post the stacktrace?
I don`t think "render" is causing the error, I think it happens earlier on in the callstack.
#tested this, it is valid code
def mytest
data = ["1","2","3"]
render :json => data
end
reports.rb
def method
if self.name == "Maintenance History"
'maintenance_history'
elsif self.name == "Outstanding Maintenance"
'outstanding_maintenance'
elsif self.name == "Idle Time Report"
'idle_time_report'
end
end
def maintenance_history
maintenance_history.where(....)
end
def outstanding_maintenance
outstanding_maintenance.where(....)
end
def idle_time_report
idle_time_report.where(....)
end
reports_controller
def show
#report = Report.find(params[:id])
respond_to do |format|
format.html # show.html.erb
show.html.haml
= render #report.method, :report => #report
I would like to format the html table in my view with the following tag %table.table.datatable#datatable
This:
%table.table.datatable#datatable
= render #report.method, :report => #report
does not work...
If I understand your issue correctly, it's that the different tables require different styles depending on the report. Just as you're using the name of the report in the controller to determine the scope, you could use some attribute of the report in the view to add a class or other identifying attribute to the HTML.
As a simple example, you could create a helper for your view exactly like your method controller method, like:
# some helper for the reports
module ReportsHelper
# the `method` method from your controller, migrated to a helper
def report_table_class(report)
if report.name == "Maintenance History"
'maintenance_history'
elsif report.name == "Outstanding Maintenance"
'outstanding_maintenance'
elsif report.name == "Idle Time Report"
'idle_time_report'
end
end
end
Then in your view, you could use that to demarcate the table or a parent element, which you could use as a target for your style selector:
%table#datatable{:class => ['table', 'datatable', report_table_class(#report)]}
And finally in your CSS:
table.maintenance_history {
// style accordingly
}
table.idle_time_report {
// style accordingly
}