ActionController::ParameterMissing in LoansController#new - ruby-on-rails

I know there are lots of these errors discussed and I have read many of them with no success so this is not a first step by posting. I am a developer but new to Ruby so any guidance would be appreciated thanks!
I have 2 models Loan and Growthyear and Loan has_many :growthyears
Existing loans are displaying and I can edit them but trying to create a new Loan now gets this error ever since I added the nested association growthyears.
I can post the new.html.erb but I don't believe it is even getting that far.
ActionController::ParameterMissing in LoansController#new
param is missing or the value is empty: loan
Extracted source (around line #249):
value
else
raise ParameterMissing.new(key)
end
end
loan.rb
class Loan < ActiveRecord::Base
has_many :growthyears
accepts_nested_attributes_for :growthyears, reject_if: proc { |attributes| attributes['growth'].blank? }, allow_destroy: true
end
growthyear.rb
class Growthyear < ActiveRecord::Base
belongs_to :loan
validates_presence_of :growth
end
loans_controller.rb
class LoansController < ApplicationController
def show
#loan = Loan.find(params[:id])
end
def home
end
def destroy
Loan.find(params[:id]).destroy
flash[:success] = "Loan (" + params[:id] + ") deleted " + Time.now.localtime("+10:00").to_s
redirect_to loans_url
end
def index
#loans = Loan.paginate(page: params[:page], :per_page => 5)
end
def new
#loan = Loan.new(user_params)
#loan.growthyears.build
end
def create
#loan = Loan.new(user_params) # Not the final implementation!
if #loan.save
flash[:success] = "(" + #loan.id.to_s + ") " + #loan.name + " New Loan Saved! " + Time.now.localtime("+10:00").to_s
render 'edit'
else
render 'new'
end
end
def update
#loan = Loan.find(params[:id])
#loan.yeargrowth = params[:yearlygrowth]
if #loan.update_attributes(user_params)
flash[:success] = "(" + #loan.id.to_s + ") " + #loan.name + " Loan updated " + Time.now.localtime("+10:00").to_s
end
redirect_to edit_loan_path(#loan.id)
end
def edit
#loan = Loan.find(params[:id])
flash[:success] = "(" + #loan.id.to_s + ") " + #loan.name + " Loan retrieved " + Time.now.localtime("+10:00").to_s
end
private
def user_params
params.require(:loan).permit(:name, :CCV, :Loan, :IRV, :ODV, :period, :simLowInt, :simHighInt, :bSimActive, :LoanBook, growthyears_attributes: [:growth, :id, :_destroy] )
end
end

you should declare only Loan.new, because in new you only initliazie this object so instead this
def new
#loan = Loan.new(user_params)
#loan.growthyears.build
end
put this:
def new
#loan = Loan.new
#loan.growthyears.build
end

Related

How to set karma to appropriate user

I'm trying to add a user karma feature to my app and I'm almost done, just that the karma is being awarded to a different user.
NB, My like system is from scratch and not acts_as_votable.
What I want:
When a user upvotes a book, I want a +1 karma be awarded to the
book.user
If a user's books are downvoted more then they upvoted, I want such
user have negative karma.
What I'm getting:
When a book is upvoted, the user who upvoted the book gets the +1
karma instead of the book.user.
When a user with 0 karma gets his/her book downvoted, the karma incrment by 1 instead of decrementing.
class AddKarmaToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :karma, :integer, default: 0
end
end
My code:
vote.rb
class Vote < ApplicationRecord
belongs_to :user
belongs_to :book
validates_uniqueness_of :user_id, scope: :book_id
after_create :increment_vote, :add_karma
after_destroy :decrement_vote, :remove_karma
private
def increment_vote
field = self.upvote ? :upvotes : :downvotes
Book.find(self.book_id).increment(field).save
end
def decrement_vote
field = self.upvote ? :upvotes : :downvotes
Book.find(self.book_id).decrement(field).save
end
def add_karma
user = User.find(self.user_id)
user.increment(:karma, 1).save
end
def remove_karma
user = User.find(self.user_id)
user.decrement(:karma, 1).save
end
end
votes_controller.rb
class VotesController < ApplicationController
def create
book_id = params[:book_id]
vote = Vote.new
vote.book_id = params[:book_id]
vote.upvote = params[:upvote]
vote.user_id = current_user.id
#check if vote by this user exists
existing_vote = Vote.where(user_id: current_user.id, book_id: book_id)
#new_vote = existing_vote.size < 1
respond_to do |format|
format.js {
if existing_vote.size > 0
#destroy existing vote
existing_vote.first.destroy
else
#save new vote
if vote.save
#success = true
else
#success = false
end
# #total_upvotes = #book.upvotes
# #total_downvotes = #book.downvotes
end
#book = Book.find(book_id)
#is_upvote = params[:upvote]
render "votes/create"
}
end
end
private
def vote_params
params.require(:vote).permit(:upvote, :book_id)
end
end
First of all when using active record relations you don't need to call Model.find in the class, just call the relation with it's name:
def increment_vote
field = self.upvote ? :upvotes : :downvotes
book.increment(field).save
end
def add_karma
user.increment(:karma, 1).save
end
In add_karma and remove_karma you are referencing the user that the vote belongs to, and not the user that owns the book. To achieve your goal you should also increment and decrement karma on the book's owner:
def add_karma
user.increment(:karma, 1).save
book.user.increment(:karma, self.upvote ? 1 : -1).save
end
def remove_karma
user.increment(:karma, 1).save
book.user.decrement(:karma, 1).save
end
You could rewrite your controller to simplify the code:
class VotesController < ApplicationController
def create
#vote = current_user.votes.find_or_initialize_by vote_params[:book_id]
#vote.assign_attributes vote_params
#success = #vote.save
# instead of #book = #vote.book just use #vote.book in your view
#book = #vote.book
# instead of #is_upvote you can use #vote.upvote in your view
#is_upvote = #vote.upvote
respond_to do |format|
format.js { render 'votes/create'}
end
end
private
def vote_params
params.require(:vote).permit(:upvote, :book_id)
end
end

Manually assigning parent ID with has_many/belongs_to association in custom class

I'm using a custom class to make AR instances from Feedjirra. I can't get the children instances to relate to their parent objects.
Show has_many :episodes -
Episode belongs_to :show -
show_id is always nil.
RSpec logs #show.id and #episode.show_id as equal to one another. However when I run episode = Episode.first after running an import in development, the episode has its show_id set to nil.
#show = Show.new
#show.name = #feed.title
#show.description = #feed.description
...
if #show.save
puts "#show.id: #{#show.id}"
end
#episodes = []
#feed.entries.each do |item|
#episodes.push(item)
end
#episodes.each do |item|
#episode = #show.episodes.new
#episode.name = item.title
#episode.description = item.summary
...
if #episode.save
puts "#episode.show_id: #{#episode.show_id}"
end
end
I tried using #episode = #show.episodes.create, as well as #episode = Episode.new with #episode.show_id = #show.id. They all log matching IDs but show_id is still nil on the instances. Every other column is filled in correctly.
I thought the issue may have had to do with using add_foreign_key:
class AddShowToEpisodes < ActiveRecord::Migration
def change
add_reference :episodes, :show, index: true
add_foreign_key :episodes, :shows, column: :show_id
end
end
So I removed that and used the standard foreign_key: true but it had no effect.
class RemoveShowFromEpisodes < ActiveRecord::Migration
def change
remove_column :episodes, :show_id
end
end
class AddShowBackToEpisodes < ActiveRecord::Migration
def change
add_reference :episodes, :show, index: true, foreign_key: true
end
end
Here's the full code in case it helps.
importers_controller.rb:
class Admin::ImportersController < Admin::ApplicationController
before_action :set_importer, only: [:show, :edit, :update, :destroy]
def index
#importers = policy_scope(Importer)
end
def show
end
def new
#importer = Importer.new
authorize #importer
end
def create
#importer = Importer.new(importer_params)
authorize #importer
if #importer.save
require "subscription_importer"
SubscriptionImporter.new(#importer)
flash[:notice] = "Importer added."
redirect_to admin_importers_path
else
flash[:error] = "Importer not added."
render "new"
end
end
def edit
end
def update
end
def destroy
end
private
def set_importer
#importer = Importer.find(params[:id])
authorize #importer
end
def importer_params
params.require(:importer).permit(:name, :url, :source)
end
end
subscription_importer.rb:
class SubscriptionImporter
def initialize(importer)
#importer = importer
#feed = Feedjira::Feed.fetch_and_parse #importer.url
if #importer.source === "iTunes"
itunes_parser(#importer)
end
end
def itunes_parser(importer)
#importer = importer
# Parser
#feed = Feedjira::Feed.fetch_and_parse #importer.url
# Show
#show = Show.new
#show.name = #feed.title
#show.description = #feed.description
#show.logo = #feed.itunes_image
#show.explicit = explicit_check(#feed.itunes_explicit)
#show.genre = #feed.itunes_categories
#show.tags = #feed.itunes_keywords
#show.url = #feed.url
#show.language = #feed.language
if #show.save
puts "Show import succeeded"
puts "#show.id: #{#show.id}"
else
puts "Show import failed"
end
# Episodes
#episodes = []
#feed.entries.each do |item|
#episodes.push(item)
end
#episodes.each do |item|
#episode = #show.episodes.new
#episode.name = item.title
#episode.description = item.summary
#episode.release = item.published
#episode.image = item.itunes_image
#episode.explicit = explicit_check(item.itunes_explicit)
#episode.tags = item.itunes_keywords
#episode.url = item.enclosure_url
#episode.duration = item.itunes_duration
if #episode.save
puts "Episode import succeeded"
puts "#episode.show_id: #{#episode.show_id}"
else
puts "Episode import failed"
end
end
end
def explicit_check(string)
if string == "yes" || "Yes"
true
else
false
end
end
end
create_importer_spec.rb:
require "rails_helper"
RSpec.feature "Admins can create importers" do
let(:user) { FactoryGirl.create(:user, :admin) }
context "admins" do
before do
login_as(user)
visit "/"
click_link "Admin"
click_link "Importers"
click_link "New Importer"
end
scenario "with valid credentials" do
fill_in "Name", with: "The Stack Exchange Podcast"
fill_in "Url", with: "https://blog.stackoverflow.com/feed/podcast/" # Needs stubbing
select "iTunes", from: "Source"
click_button "Create Importer"
expect(page).to have_content "Importer added"
expect(page).to have_content "The Stack Exchange Podcast"
end
scenario "with invalid credentials" do
fill_in "Name", with: ""
fill_in "Url", with: ""
click_button "Create Importer"
expect(page).to have_content "Importer not added"
end
end
end
I think the episodes functionality in your SubscriptionImporter class is causing the problem...
#episodes = []
#feed.entries.each do |item|
#episodes.push(item) #-> each "#episodes" is a FeedJirra object
end
#episodes.each do |episode|
#-> you're now creating an episode in the same call as show, which will either mean that show is not persisted or perhaps some other error
end
I would personally limit the SubscriptionImporter functionality to only return data. You should be parsing that data through the respective models:
#app/controllers/admin/importers_controller.rb
class Admin::ImportersController < Admin::ApplicationController
def create
#import = Importer.new import_params
if #import.save
#import.parse_show if #import.itunes?
end
end
private
def import_params
params.require(:importer).permit(:name, :url, :source)
end
end
#app/models/importer.rb
class Importer < ActiveRecord::Base
def feed
return false unless itunes?
origin = Feedjirra::Feed.fetch_and_parse(self.url)
return {
name: origin.title,
description: origin.description,
logo: origin.itunes_image,
explicit: explicit_check(origin.itunes_explicit),
genre: origin.itunes_categories,
tags: origin.itunes_keywords,
url: origin.url,
language: origin.language,
entries: origin.entries
}
end
def parse_show
Show.create(feed)
end
def itunes?
self.source == "iTunes" #-> true/false
end
private
def explicit_check
string == "yes" || "Yes" #-> true/false
end
end
#app/models/show.rb
class Show < ActiveRecord::Base
has_many :episodes
attr_accessor :entries
after_create :create_episodes #-> might not persist entries
def create_episodes
if self.entries.any?
self.entries.each do |item|
self.episodes.create({
name: item.title
description: item.summary,
release: item.published,
image: item.itunes_image,
explicit: explicit_check?(item.itunes_explicit),
tags: item.itunes_keywords,
url: item.enclosure_url,
duration: item.itunes_duration
})
end
end
end
private
def explicit_check?
string == "yes" || "Yes"
end
end
The above will allow you to create an #importer, pull the feed from it, and populate Show & Episode models with the returned data.
Whilst this should resolve your issue, you need to consider OOP -- making each element an object.
Update
If you wanted to objectify this even more, there is a simple pattern to adopt:
Importer is all you need to save -- everything else should happen around this
Show + Episode could be the same class / table for all I know
With this in mind, you could do the following:
#app/controllers/admin/importers_controller.rb
class Admin::ImportersController < Admin::ApplicationController
def create
#import = Importer.new import_params
#import.save
end
private
def import_params
params.require(:importer).permit(:name, :url, :source)
end
end
#app/services/feed.rb
class Feed
attr_reader :params, :show, :episode, :origin
def initialize(params)
#params = params
end
def origin
#origin = Feedjirra::Feed.fetch_and_parse params[:source]
end
def show
#show = ShowHelper.new #origin
end
def episodes
#show.episodes
end
end
#app/services/show_helper.rb
class ShowHelper
attr_reader :origin
def initialize(origin)
#origin = origin
end
def name
#origin.title
end
def description
#origin.summary || #origin.description
end
def logo
#origin.itunes_image
end
def explicit
%r{^yes$} =~ #origin.itunes_explicit
end
def genre
#origin.itunes_categories
end
def tags
#origin.itunes_keywords
end
def url
#origin.url
end
def language
#origin.language
end
def episodes
#origin.entries
end
end
#app/models/importer.rb
class Importer < ActiveRecord::Base
after_create :parse_show, if: "itunes?"
validates :source, :url, :name, presence: true
def itunes?
source == "iTunes"
end
def feed
#feed = Feed.new(self)
end
private
def parse_show
#show = Show.new(feed.show) if feed && feed.show
if #show.save && #show.entries.any?
#show.entries.each do |entry|
#show.episodes.create ShowHelper.new(entry)
end
end
end
end

Undefined method error, but my method is defined?

When I run my app, I get an error that states: undefined local variable or method `signup' for #, but I'm not sure why this is happening. According to the code below, Signup is a new class that I've defined.
Thanks for your help!
Controller code:
class SignupsController < ApplicationController
def new
#signup = Signup.new
end
def create
#signup = Signup.new(signup_params)
if #signup.save
signup.add_subscrip
else
redirect_to new_signup_path
end
end
end
Model code:
class Signup < ActiveRecord::Base
validates :email, presence: true, format: { with: /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i }
validates :name, presence: true, length: { maximum: 50 }
def add_subscrip
connection = GoogleDrive.login(ENV['g_username'], ENV['g_password'])
ss = connection.spreadsheet_by_title(ENV['spreadsheet_title'])
ws = ss.worksheets[0]
row = 3 + ws.num_rows
ws[row, 1] = self.name
ws[row, 2] = Time.new
ws[row, 3] = self.email
ws.save
end
end
In your create method
def create
#signup = Signup.new(signup_params)
if #signup.save
signup.add_subscrip
else
redirect_to new_signup_path
end
end
My sense is that
signup.add_subscrip
needs to be
#signup.add_subscrip

Rails - Object values not being accessible on a attribute writer method

I have a Study model which have many fields, but I'm having troubles with 1
profesion_name
so in my study model I have this
class Study < ActiveRecord::Base
attr_accessible :profesion_related, :profesion_name
attr_accessor :profesion_related
def profesion_related=(id)
if id.present?
if self.study_type_id == 4
if self.country_id == 170
#some code here
else
profesion_parent = Profesion.find(id)
new_profesion = Profesion.create({g_code: profesion_parent.g_code, mg_code: profesion_parent.mg_code, name: self.profesion_name})
self.profesion = new_profesion
end
end
end
end
end
but I'm getting an error on the line that create a Profesion, because self.profesion_name is nil
if in my controller I do this
def create
#study = Study.new(params[:study])
respond_to do |format|
#here
puts #study.to_yaml
if #study.save
.....
end
I will see in the console that profesion_name has a value
but if I do this
class Study < ActiveRecord::Base
...
def profesion_related=(id)
puts self.to_yaml
....
end
end
I can see that self.profesion_name is empty
Why could this be happening?

Prevent ActionMailer to strip repeating spaces in plain message

I'm trying to have an table in text mail, so I write some helpers:
module MailerHelper
def field_width(text, width)
' ' * (width - text.length) + text
end
def cell(text, width)
output = '| ' + field_width(text, width-2) + " |\n"
output << '+-' + '-'*(width-2) + '-+'
end
end
Then in view I write it like this:
<%= cell 'Test', 10 %>
But that what I get (according to letter_opener) is:
| Test |
+----------+
As can you see, the spaces that are repeating before Test. My question is how to prevent ActionMailer (or anything else what is destroying my beautiful table) from doing that.
Mailer code:
def remind(client, invoices)
#client = client
#company = #client.company
#invoices = invoices.to_a
days_left = #invoices.first.pay_date - Date.today
message = #client.group.messages.find_by_period days_left.to_i
raise 'No messages for this invoices.' if message.nil?
#template = message.template || if days_left < 0
t 'message.before'
elsif days_left > 0
t 'message.after'
else
t 'message.today'
end
#text = liquid_parse #template
#html = markdown_parse #text
mail(:to => #client.email, :subject => t('message.title'))
end
private
def markdown_parse(text)
markdown = Redcarpet::Markdown.new Redcarpet::Render::HTML,
:autolink => true, :space_after_headers => true
markdown.render text
end
def liquid_parse(text)
renderer = Liquid::Template.parse text
renderer.render 'company' => #company, 'invoice' => #invoice, 'client' => #client
end
I've found bug. It was caused by Premailer what I use to inline CSS in HTML part.
class InlineCSSInterceptor
def self.delivering_email(message)
#message.text_part.body = Premailer.new(message.text_part.body.to_s, with_html_string: true).to_plain_text # this is line causing the problem.
message.html_part.body = Premailer.new(message.html_part.body.to_s, with_html_string: true).to_inline_css
end
end
Mailer.register_interceptor InlineCSSInterceptor

Resources