uploaded_song_datatable.rb --which is used for showing list of song in datatable.
class UploadedSongDatatable < AjaxDatatablesRails::Base
include AjaxDatatablesRails::Extensions::Kaminari
def_delegator :#view, :best_in_place
def_delegator :#view, :link_to
def_delegator :#view, :uploaded_song_path
def_delegator :#view, :autocomplete_album_name_albums_path
def_delegator :#view, :autocomplete_artist_name_artists_path
def_delegator :#view, :autocomplete_genre_name_genres_path
def_delegator :#view, :year_list
def_delegator :#view, :content_tag
def_delegator :#view, :image_tag
def sortable_columns
#sortable_columns ||= [
'UploadedSong.title',
'UploadedSong.artist',
'UploadedSong.album',
'UploadedSong.genre'
]
end
def searchable_columns
#searchable_columns ||= [
'UploadedSong.title',
'UploadedSong.artist',
'UploadedSong.album',
'UploadedSong.genre'
]
end
private
def data
records.map do |record|
[
# best_in_place(record, , :as => :checkbox, :collection => ['<input name="mark[]" type="checkbox">'.html_safe, '<input type="checkbox" checked="true">'.html_safe]),
nil,
"<input type='checkbox' class='checkBoxClass' name=\"songids[]\" value='#{record.id}' >",
best_in_place(record, :is_explicit, :as => :checkbox, :collection => ['<input type="checkbox">'.html_safe, '<input type="checkbox" checked="true">'.html_safe] , url: uploaded_song_path(record, field_to_update: 'is_explicit')),
best_in_place(record, :title, :display_with => lambda { |v| v.blank? ? "( No title )" : v }, url: uploaded_song_path(record, field_to_update: 'title')),
best_in_place(record, :artist, :display_with => lambda { |v| v.blank? ? "( No artist )" : v }, url: uploaded_song_path(record, field_to_update: 'artist'), html_attrs: { "data-autocomplete" => autocomplete_artist_name_artists_path, "object_id" => record.id.to_s }),
best_in_place(record, :album, :display_with => lambda { |v| v.blank? ? "( No album )" : v }, url: uploaded_song_path(record, field_to_update: 'album'), html_attrs: { "data-autocomplete" => autocomplete_album_name_albums_path }),
best_in_place(record, :genre, :display_with => lambda { |v| v.blank? ? "( No genre )" : v }, url: uploaded_song_path(record, field_to_update: 'genre'), html_attrs: { "data-autocomplete" => autocomplete_genre_name_genres_path }),
best_in_place(record, :year, :as => :select, :collection => year_list, :display_with => lambda { |v| v.blank? ? "( No year )" : v }, url: uploaded_song_path(record, field_to_update: 'year')),
best_in_place(record, :track, :display_with => lambda { |v| v.blank? ? "( No track )" : v }, url: uploaded_song_path(record, field_to_update: 'track')),
best_in_place(record, :comment, :display_with => lambda { |v| v.blank? ? "( No comment )" : v }, url: uploaded_song_path(record, field_to_update: 'comment')),
if record.cover_id.blank?
link_to("No Cover", "#cover_modal", data: {song_id: record.id, toggle: "modal", multiqueue: 'false'})
else
link_to("#") do
image_tag(record.cover.cover_pic.url, href: "#cover_modal", height: '50', width: '50', data: {song_id: record.id, toggle: "modal", src: record.cover.cover_pic.url, multiqueue: 'false'})
end
end,
link_to(uploaded_song_path(record), method: :delete, data: { confirm: "Are you sure to delete the song ?"}) do
content_tag :span, '', class: "glyphicon glyphicon-trash glyphicon-red"
end
]
end
end
def get_raw_records
UploadedSong.all
end
end
uploaded_song_controller.rb
require 'taglib'
class UploadedSongsController < ApplicationController
before_action :authenticate_user!
authorize_resource
respond_to :json, :html, :js
def index
if params[:from_modal]
sleep(10)
flash[:notice] = "Click 'Refresh', to view recently uploaded songs."
end
#songs = UploadedSong.count
respond_to do |format|
format.html
format.json { render json: UploadedSongDatatable.new(view_context) }
end
end
def new
#song = UploadedSong.new
end
def create
Rails.logger.debug params[:file]
extraction_path = Pathname.new("#{Rails.root}/public")
file_ext = File.extname(params[:file].original_filename)
original_file_name = params[:file].original_filename
tmp_file_base_name = File.basename(params[:file].path)
uploaded_tmp_file = "#{extraction_path}/#{tmp_file_base_name}"
uploaded_file = "#{extraction_path}/#{original_file_name}"
if params[:file].content_type == "application/zip"
Rails.logger.debug "moving #{params[:file].path} to #{extraction_path}"
FileUtils.mv(params[:file].path, extraction_path)
Rails.logger.debug "file moved"
if File.rename(uploaded_tmp_file, uploaded_file)
Resque.enqueue(ZipExtractor, uploaded_file, extraction_path.to_s, true, false)
Rails.logger.debug "Background job started"
head 200
else
File.delete(uploaded_tmp_file) if File.exist?(uploaded_tmp_file)
end
elsif %w(.mp3 .ogg .mp4 .m4a).include?(file_ext)
FileUtils.mv(params[:file].path, extraction_path)
if File.rename(uploaded_tmp_file, uploaded_file)
Rails.logger.info "renaming #{tmp_file_base_name} to #{original_file_name}"
Resque.enqueue(ZipExtractor, false, uploaded_file, false, false)
head 200
else
File.delete(uploaded_tmp_file) if File.exist?(uploaded_tmp_file)
head 200
end
else
File.delete(params[:file].path) if File.exist?(params[:file].path)
head 200
end
end
def edit
#song = UploadedSong.find(params[:id])
end
def update
#song = UploadedSong.find(params[:id])
#song.field_to_update = (params[:field_to_update])
if #song.update_attributes(uploaded_song_params)
Resque.enqueue(ZipExtractor, #song.id, false, false, #song.field_to_update)
end
respond_with_bip #song
end
def destroy
#song = UploadedSong.find(params[:id])
#song.destroy!
unless #song.cover_id.blank?
cover = Cover.find(#song.cover_id)
cover.destroy!
end
if session[:ids] == nil
respond_to do |format|
format.html { redirect_to uploaded_songs_url, notice: 'Song was successfully destroyed.' }
format.json { head :no_content }
end
else
session[:ids].delete(#song.id)
respond_to do |format|
format.html { redirect_to uploaded_songs_url, notice: 'Song was successfully destroyed.' }
format.json { head :no_content }
end
end
end
private
def uploaded_song_params
params.require(:uploaded_song).permit(:title, :artist, :album, :year, :track, :genre, :comment, :song_name, :attachment, :is_explicit)
end
def set_session_for_ids
if session[:ids] == nil
session[:ids] = Array.new
end
end
def update_music_metadata?(song)
TagLib::FileRef.open(song.attachment_url) do |fileref|
unless fileref.null?
tag = fileref.tag # true is for writing.
tag.title = song.title
tag.artist = song.artist
tag.album = song.album
tag.year = song.year.to_i
tag.track = song.track.to_i
tag.genre = song.genre
tag.comment = song.comment
if fileref.save
return true
else
return false
end
end
end
end
def update_song_name?(song)
file_handle = File.open(song.song_path)
dir_location = File.dirname(song.song_path)
file_ext = File.extname(song.song_path)
song_name = song.song_name + file_ext
song_path = dir_location + "/#{song_name}"
attachment = File.rename_file(file_handle, song_path)
if song.update_attributes({attachment: attachment, song_name: song_name, song_path: song_path})
return true
else
return false
end
end
end
uploaded_song.rb
require 'file_size_validator'
class UploadedSong < ActiveRecord::Base
belongs_to :cover
mount_uploader :attachment, AttachmentUploader
skip_callback :commit, :after, :remove_attachment!, if: Proc.new{ |s| s.file_keep == true }
validates :attachment, :file_size => { less_than: 200.megabytes }
attr_accessor :file_keep, :field_to_update
end
zip_extractor.rb
require 'taglib'
require 'zip'
class ZipExtractor
#queue = :songs_queue
def self.perform path_to_zip, destination_path, delete = false, field_to_update
if !path_to_zip.blank? and delete and !destination_path.blank? and !field_to_update
unzip(path_to_zip, destination_path)
Dir.glob("#{destination_path}" + '/*') do |music_file|
base_file_name = File.basename(music_file)
next if base_file_name.casecmp("__macosx") == 0
process_song(music_file)
end
end
if !path_to_zip and !delete and !destination_path.blank? and !field_to_update
process_song(destination_path)
end
if !path_to_zip.blank? and !delete and !destination_path and !field_to_update.blank?
log("processing song details update")
song = UploadedSong.find(path_to_zip)
song_details = nil
TagLib::FileRef.open(song.attachment_url) do |fileref|
unless fileref.null?
tag = fileref.tag
case field_to_update.to_s
when "title"
tag.title = song.title
when "artist"
tag.artist = song.artist
when "album"
tag.album = song.album
when "year"
tag.year = song.year.to_i
when "track"
tag.track = song.track.to_i
when "genre"
tag.genre = song.genre
when "comment"
tag.comment = song.comment
else
log 'No parameters for "field_to_update".'
end
unless fileref.save
TagLib::FileRef.open(song.attachment_url) do |fileref|
unless fileref.null?
tag = fileref.tag
song_details = {
title: tag.title,
artist: tag.artist,
album: tag.album,
year: tag.year,
track: tag.track,
genre: tag.genre,
comment: tag.comment,
is_explicit: false
}
end
end
if song_details[:title].downcase.include? 'explicit'
song_details[:is_explicit] = true
end
song.update_attributes(song_details)
end
end
end
end
end
def self.process_song(destination_path)
if %w(.mp3 .ogg .mp4 .m4a).include? File.extname(destination_path)
if %w(.ogg .mp4 .m4a).include? File.extname(destination_path)
destination_path = convert_video_to_audio(destination_path)
end
if %w(.mp3).include? File.extname(destination_path)
process_mp3(destination_path)
else
delete_file(destination_path)
end
else
delete_file(destination_path)
end
end
def self.process_mp3(destination_path)
song_details = extract_metadata(destination_path)
rename_file = File.dirname(destination_path) + "/1-----" + File.basename(destination_path)
extension = File.extname(destination_path)
cover_file_name = nil
rename = File.rename(destination_path, rename_file)
if rename == 0
transcoded_movie, cover_file_name = transcode_file(rename_file, destination_path)
if transcoded_movie.valid?
delete_file(rename_file)
song_details[:attachment] = File.open(destination_path) if File.exist?(destination_path)
# cover = nil
p song_details[:attachment]
unless cover_file_name.nil?
cover = Cover.new({name: File.basename(cover_file_name), cover_pic: File.open(cover_file_name)}) if File.exist?(cover_file_name)
end
song = UploadedSong.new(song_details)
if !cover.blank?
if cover.save
delete_file(cover_file_name)
song.cover_id = cover.id
if song.save
delete_file(destination_path)
end
end
else
p 9999999999999999999999999999999999999999999999999999
p song.valid?
p song.save
p song.errors.any?
p song.errors.full_messages
p 9999999999999999999999999999999999999999999999999999
if song.save!
delete_file(destination_path)
end
end
else
delete_file(destination_path)
delete_file(rename_file)
end
else
delete_file(destination_path)
end
end
def self.convert_video_to_audio(destination_path)
log "Found video file. Converting video to audio."
movie = FFMPEG::Movie.new(destination_path)
if movie.valid?
file_name_with_no_ext = File.basename(destination_path, "#{File.extname(destination_path)}")
out_file = "#{File.dirname(destination_path)}/#{file_name_with_no_ext}.mp3"
out_movie = movie.transcode(out_file)
if out_movie.valid?
delete_file(destination_path)
destination_path = out_file
end
end
return destination_path
end
def self.extract_metadata(destination_path)
log("extracting metadata from media file")
song_details = nil
TagLib::FileRef.open(destination_path) do |fileref|
unless fileref.null?
tag = fileref.tag
song_details =
{
title: tag.title.blank? ? 'Single' : tag.title,
artist: tag.artist.blank? ? 'Single' : tag.artist,
album: tag.album.blank? ? 'Single' : tag.album,
year: tag.year.blank? ? '' : tag.year,
track: tag.track.blank? ? '' : tag.track,
genre: tag.genre.blank? ? '' : tag.genre,
comment: tag.comment.blank? ? '' : tag.comment,
is_explicit: false
}
if song_details[:title].downcase.include? 'explicit'
song_details[:is_explicit] = true
end
if tag.title.blank?
tag.title = "Single"
fileref.save
elsif tag.artist.blank?
tag.artist = "Single"
fileref.save
elsif tag.album.blank?
tag.album = "Single"
fileref.save
end
end
end
return song_details
end
def self.transcode_file(rename_file, destination_path)
movie = FFMPEG::Movie.new(rename_file)
cover_file_name = nil
transcoded_movie = nil
p movie.valid?
if movie.valid?
log "ffmpeg validates file #{rename_file}"
if movie.video_stream == nil
options = {audio_codec: "libmp3lame", audio_bitrate: 320, audio_sample_rate: 44100, audio_channels: 2}
else
log "removing video stream from file and extracting cover"
cover_file_name = extract_image_from_file(rename_file)
# "-vn" flag is used to remove video_stream from mp3 file
options = {audio_codec: "libmp3lame", audio_bitrate: 320, audio_sample_rate: 44100, audio_channels: 2, custom: "-vn"}
end
transcoded_movie = movie.transcode(destination_path, options)
else
log "Unable to process media file."
delete_file(rename_file)
end
return transcoded_movie, cover_file_name
end
def self.extract_image_from_file(rename_file)
cover_file_name = nil
cover_path = "#{Rails.root}/public/covers/"
TagLib::MPEG::File.open(rename_file) do |fileref|
cover_tag = fileref.id3v2_tag
cover_img = cover_tag.frame_list('APIC').first
unless cover_img.blank?
ext = cover_img.mime_type.rpartition('/')[2]
o = [('a'..'i'), ('A'..'Z')].map { |i| i.to_a }.flatten
rand_string = (1..18).map { o[rand(o.length)] }.join
cover_file_name = "#{cover_path}#{File.basename(rename_file).chomp('.mp3').gsub('1-----','')}-#{rand_string}.#{ext}"
File.open(cover_file_name, "wb") { |f| f.write cover_img.picture }
log "cover extracted from media file."
end
end
return cover_file_name
end
def self.delete_file(filename)
File.delete(filename) if File.exist?(filename)
end
def self.log(message)
Rails.logger.debug "\n*********** #{message} ***************"
end
def self.unzip(path_to_zip, destination_path)
log "unzipping #{path_to_zip} \nto #{destination_path}"
Zip::File.open(path_to_zip) do |zip_file|
# log "zip file is #{zip_file}"
zip_file.each do |f|
f_path=File.join(destination_path, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
a = zip_file.extract(f, f_path) unless File.exist?(f_path)
# log "file extraction complete"
# log a
end
log "after zip file loop"
end
# log "removing original zip file"
FileUtils.rm(path_to_zip)
# log "removed zip file from #{path_to_zip}"
end
end
in above means zip_extractor.rb I checked song.valid? it gives me false in rails 6 and error is cover must exist
and I have checked cover is nil but in rails 4 it gives true and also checked in this version also cover is nil but song saved in database in rails but not in rails 6. anyone have proper reason why it behave like this answer fast otherwise mailto: santu.essence#gmail.com
I have some service objects that use Nokogiri to make AR instances. I created a rake task so that I can update the instances with a cron job. What I want to test is if it's adding items that weren't there before, ie:
Create an Importer with a url of spec/fixtures/feed.xml, feed.xml having 10 items.
Expect Show.count == 1 and Episode.count == 10
Edit spec/fixtures/feed.xml to have 11 items
Invoke rake task
Expect Show.count == 1 and Episode.count == 11
How could I test this in RSpec, or modify my code to be more testable?
# models/importer.rb
class Importer < ActiveRecord::Base
after_create :parse_importer
validates :title, presence: true
validates :url, presence: true
validates :feed_format, presence: true
private
def parse_importer
Parser.new(self)
end
end
# models/show.rb
class Show < ActiveRecord::Base
validates :title, presence: true
validates :title, uniqueness: true
has_many :episodes
attr_accessor :entries
end
# models/episode.rb
class Episode < ActiveRecord::Base
validates :title, presence: true
validates :title, uniqueness: true
belongs_to :show
end
#lib/tasks/admin.rake
namespace :admin do
desc "Checks all Importer URLs for new items."
task refresh: :environment do
#importers = Importer.all
#importers.each do |importer|
Parser.new(importer)
end
end
end
# services/parser.rb
class Parser
def initialize(importer)
feed = Feed.new(importer)
show = Show.where(rss_link: importer.url).first
if show # add new episodes
new_episodes = Itunes::Channel.refresh(feed.origin)
new_episodes.each do |new_episode|
show.episodes.create feed.episode(new_episode)
end
else # create a show and its episodes
new_show = Show.new(feed.show) if (feed && feed.show)
if (new_show.save && new_show.entries.any?)
new_show.entries.each do |entry|
new_show.episodes.create feed.episode(entry)
end
end
end
end
end
# services/feed.rb
class Feed
require "nokogiri"
require "open-uri"
require "formats/itunes"
attr_reader :params, :origin, :show, :episode
def initialize(params)
#params = params
end
def origin
#origin = Nokogiri::XML(open(params[:url]))
end
def format
#format = params[:feed_format]
end
def show
case format
when "iTunes"
Itunes::Channel.fresh(origin)
end
end
def episode(entry)
#entry = entry
case format
when "iTunes"
Itunes::Item.fresh(#entry)
end
end
end
# services/formats/itunes.rb
class Itunes
class Channel
def initialize(origin)
#origin = origin
end
def title
#origin.xpath("//channel/title").text
end
def description
#origin.xpath("//channel/description").text
end
def summary
#origin.xpath("//channel/*[name()='itunes:summary']").text
end
def subtitle
#origin.xpath("//channel/*[name()='itunes:subtitle']/text()").text
end
def rss_link
#origin.xpath("//channel/*[name()='atom:link']/#href").text
end
def main_link
#origin.xpath("//channel/link/text()").text
end
def docs_link
#origin.xpath("//channel/docs/text()").text
end
def release
#origin.xpath("//channel/pubDate/text()").text
end
def image
#origin.xpath("//channel/image/url/text()").text
end
def language
#origin.xpath("//channel/language/text()").text
end
def keywords
keywords_array(#origin)
end
def categories
category_array(#origin)
end
def explicit
explicit_check(#origin)
end
def entries
entry_array(#origin)
end
def self.fresh(origin)
#show = Itunes::Channel.new origin
return {
description: #show.description,
release: #show.release,
explicit: #show.explicit,
language: #show.language,
title: #show.title,
summary: #show.summary,
subtitle: #show.subtitle,
image: #show.image,
rss_link: #show.rss_link,
main_link: #show.main_link,
docs_link: #show.docs_link,
categories: #show.categories,
keywords: #show.keywords,
entries: #show.entries
}
end
def self.refresh(origin)
#show = Itunes::Channel.new origin
return #show.entries
end
private
def category_array(channel)
arr = []
channel.xpath("//channel/*[name()='itunes:category']/#text").each do |category|
arr.push(category.to_s)
end
return arr
end
def explicit_check(channel)
string = channel.xpath("//channel/*[name()='itunes:explicit']").text
if string === "yes" || string === "Yes"
true
else
false
end
end
def keywords_array(channel)
keywords = channel.xpath("//channel/*[name()='itunes:keywords']/text()").text
arr = keywords.split(",")
return arr
end
def entry_array(channel)
arr = []
channel.xpath("//item").each do |item|
arr.push(item)
end
return arr
end
end
class Item
def initialize(origin)
#origin = origin
end
def description
#origin.xpath("*[name()='itunes:subtitle']").text
end
def release
#origin.xpath("pubDate").text
end
def image
#origin.xpath("*[name()='itunes:image']/#href").text
end
def explicit
explicit_check(#origin)
end
def duration
#origin.xpath("*[name()='itunes:duration']").text
end
def title
#origin.xpath("title").text
end
def enclosure_url
#origin.xpath("enclosure/#url").text
end
def enclosure_length
#origin.xpath("enclosure/#length").text
end
def enclosure_type
#origin.xpath("enclosure/#type").text
end
def keywords
keywords_array(#origin.xpath("*[name()='itunes:keywords']").text)
end
def self.fresh(entry)
#episode = Itunes::Item.new entry
return {
description: #episode.description,
release: #episode.release,
image: #episode.image,
explicit: #episode.explicit,
duration: #episode.duration,
title: #episode.title,
enclosure_url: #episode.enclosure_url,
enclosure_length: #episode.enclosure_length,
enclosure_type: #episode.enclosure_type,
keywords: #episode.keywords
}
end
private
def explicit_check(item)
string = item.xpath("*[name()='itunes:explicit']").text
if string === "yes" || string === "Yes"
true
else
false
end
end
def keywords_array(item)
keywords = item.split(",")
return keywords
end
end
end
Before anything else, good for you for using service objects! I've been using this approach a great deal and find POROs preferable to fat models in many situations.
It appears the behavior you're interested in testing is contained in Parser.initialize.
First, I'd create a class method for Parser called parse. IMO, Parser.parse(importer) is clearer about what Parser is doing than is Parser.new(importer). So, it might look like:
#services/parser.rb
class Parser
class << self
def parse(importer)
#importer = importer
#feed = Feed.new(importer)
if #show = Show.where(rss_link: importer.url).first
create_new_episodes Itunes::Channel.refresh(#feed.origin)
else
create_show_and_episodes
end
end # parse
end
end
Then add the create_new_episodes and create_show_and_episodes class methods.
#services/parser.rb
class Parser
class << self
def parse(importer)
#importer = importer
#feed = Feed.new(importer)
if #show = Show.where(rss_link: #importer.url).first
create_new_episodes Itunes::Channel.refresh(#feed.origin)
else
create_show_and_episodes
end
end # parse
def create_new_episodes(new_episodes)
new_episodes.each do |new_episode|
#show.episodes.create #feed.episode(new_episode)
end
end # create_new_episodes
def create_show_and_episodes
new_show = Show.new(#feed.show) if (#feed && #feed.show)
if (new_show.save && new_show.entries.any?)
new_show.entries.each do |entry|
new_show.episodes.create #feed.episode(entry)
end
end
end # create_show_and_episodes
end
end
Now you have a Parser.create_new_episodes method that you can test independently. So, your test might look something like:
require 'rspec_helper'
describe Parser do
describe '.create_new_episodes' do
context 'when an initial parse has been completed' do
before(:each) do
first_file = Nokogiri::XML(open('spec/fixtures/feed_1.xml'))
#second_file = Nokogiri::XML(open('spec/fixtures/feed_2.xml'))
Parser.create_show_and_episodes first_file
end
it 'changes Episodes.count by 1' do
expect{Parser.create_new_episodes(#second_file)}.to change{Episodes.count}.by(1)
end
it 'changes Show.count by 0' do
expect{Parser.create_new_episodes(#second_file)}.to change{Show.count}.by(0)
end
end
end
end
Naturally, you'll need feed_1.xml and feed_2.xml in the spec\fixtures directory.
Apologies for any typos. And, I didn't run the code. So, might be buggy. Hope it helps.
I have the following parameters
def note_params
params.require(:note).permit(
:content
)
end
Now i am trying to check of the content was empty for :content i am passing this to a service object
def add_note_to_plan
unless #note_params.content.empty?
puts "======================================================"
note = Note.new(
note_params.merge(
plan: #plan,
user: #current_user
)
)
note.save
end
puts "=================== outside ==================================="
end
Service Object
class PlanCreator
def initialize(current_user, venue_params, plan_params, note_params)
#current_user = current_user
#venue_params = venue_params
#plan_params = plan_params
#note_params = note_params
end
attr_reader :venue, :plan
def create
#venue = new_or_existing_venue
#plan = new_or_existing_plan
save_venue && save_plan && add_current_user_to_plan && add_note_to_plan
end
def errors
{
venue: venue_errors,
plan: plan_errors,
note: note_errors
}
end
private
attr_reader :current_user, :venue_params, :plan_params, :note_params
..... Removed all the unnecessary methods
def add_note_to_plan
unless #note_params.content.empty?
puts "======================================================"
note = Note.new(
note_params.merge(
plan: #plan,
user: #current_user
)
)
note.save
end
puts "=================== outside ==================================="
end
end
Error:
NoMethodError - undefined method `content' for
{"content"=>""}:ActionController::Parameters:
Change this:
unless #note_params.content.empty?
To this:
unless #note_params[:content].empty?
ActionController's params returns a hash of parameters.
I am facing an error that when ever I try to call the function finalized_request it throws me an error saying "param is missing or the value is empty: finalizedeal". Since I am new to this I can't figure out what am I doing wrong(I am new to ROR).
Request_controller.rb
class RequestsController < ApplicationController
before_action :set_request, only: [:show, :edit, :update, :destroy]
# GET /requests
# GET /requests.json
def index
#categories_list = Category.getAll()
end
def active
user = session[:user]
#requests = Array.new
#tag = Array.new
#requests = Request.getRequestByUser(user)
#requests.each.with_index do |request, index|
if request != nil
#tag[index] = Array.new
request[:tag_id].each do |t|
#tag[index] << Tag.getTag(t)
end
end
end
end
# GET /requests/1
# GET /requests/1.json
def show
#user = User.getUser(#request[:user_id])
#tag = Array.new
#request[:tag_id].each do |cate|
#tag << Tag.getTag(cate)
end
end
# GET /requests/1/edit
def edit
#tag = Array.new
#request[:tag_id].each do |cate|
#tag << Tag.getTag(cate)
end
end
# POST /requests
def post_request
tags_arr = params[:tags] ;
#=begin
#categories = Array.new ;
#if tags != nil
# tags.each do |tag|
# category = Category.createCategoryIfNotExist(tag)
# if(category != nil)
# categories << category[:_id]
# end
# end
#end
#=end
tags = Array.new ;
if tags_arr != nil
tags_arr.each do |t|
tag = Tag.createTagIfNotExist(t)
if(tag != nil)
tags << tag[:_id]
end
end
end
request_data = request_params
user_id = session[:user]
request_data[:tag_id] = tags
request_data[:user_id] = user_id
#request_ = Request.createRequest(request_data)
if #request_
flash[:notice] = "Request Post successfully."
redirect_to :action => "active"
end
end
# PATCH/PUT /requests/1
# PATCH/PUT /requests/1.json
def update
#tags = params[:tags] ;
#categories = Array.new ;
#if tags != nil
# tags.each do |tag|
# category = Category.createCategoryIfNotExist(tag)
# if(category != nil)
# categories << category[:_id]
# end
# end
#end
tags_arr = params[:tags] ;
tags = Array.new ;
if tags_arr != nil
tags_arr.each do |t|
tag = Tag.createTagIfNotExist(t)
if(tag != nil)
tags << tag[:_id]
end
end
end
Rails.logger.info("RequestsParams: #{request_params.inspect}")
request_data = request_params
if request_data[:is_service] != "on"
request_data[:is_service] = "off"
end
user_id = session[:user]
request_data[:tag_id] = tags
request_data[:user_id] = user_id
if Request.updateRequest(#request,request_data)
flash[:notice] = "Request has been Edited successfully."
redirect_to :action => "active"
end
end
def delete_request ()
if Request.delete_request(params[:id])
flash[:notice] = "Request has been Deleted successfully."
render :json => "great"
end
end
# GET /requests
def finalize_request()
finalizedrequest = finalizedRequest_params
request = Request.getRequest(finalizedrequest[:title])
finalizedrequest[:title] = request[:title]
Request.delete_request(request[:_id])
FinalizedDeal.createFinalizedRequest(finalizedrequest)
redirect_to :action => "bookmark"
end
# GET /requests
def bookmark
user = session[:user]
#requests = Array.new
#tag = Array.new
#requests = Request.getRequestByUser(user)
#requests.each.with_index do |request, index|
if request != nil
#tag[index] = Array.new
request[:tag_id].each do |t|
#tag[index] << Tag.getTag(t)
end
end
end
end
# GET /requests
def bookmark_request
data = params[:d]
bookmarked_against_Request = Request.getRequest(1)
request_bookmarked = Request.getRequest(data)
request_bookmarked_2 = request_bookmarked
bookmarked_against_Request_2 = bookmarked_against_Request
Rails.logger.info("Bookmark 2: #{bookmarked_against_Request_2.inspect}")
#bookmarked_against_Request_2[:favourites] << request_bookmarked[:id]
#request_bookmarked_2[:favourites_of] << bookmarked_against_Request[:id]
#hello
#Request.updateRequest(request_bookmarked , request_bookmarked_2)
#Request.updateRequest(bookmarked_against_Request , bookmarked_against_Request_2)
redirect_to :action => "bookmark"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_request
#request = Request.getRequest(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def request_params
params.require(:request).permit(:title, :description, :type , :is_service , :required_user_location , :required_product_location ,:Upper_price_range , :lower_price_range , :negotiable , :type , :tags , :category_id)
end
def finalizedRequest_params
params.require(:finalizedeal).permit(:title , :description)
end
end
finalized_deal.rb
class FinalizeDeal
include Mongoid::Document
field :deal_details, type: String
field :categories, type: Array
field :owner_user, type: MongoId
field :corsponing_user, type: MongoId
field :title, type: String
field :corresponding_product, type: String
field :meeting_date, type: String
field :date_finalized, type: String
field :description, type: String
class << self
def getRequestByUser(user_id)
requests = where(user_id: user_id).to_a
if requests
requests
end
end
def getFinzlizedRequest(req)
request = find(req)
if request
request
end
end
def createFinalizedRequest(req_data)
request = self.new(req_data)
if request.save
request
end
end
def updateFinalizedRequest(request,req_data)
if request.update(req_data)
request
end
end
def delete_FinalizedRequest(req_id)
if find(req_id).delete
true
end
end
end
end
request.html.erb
div id="form-details-modal-lbms" class="reveal-modal" data-reveal>
<h3>Enter Contract Details:</h3>
<!--<form>-->
<%= form_tag({controller: "requests", action: "finalize_request"}, method: "GET",id:"post-form-lbms" ,data: {abide: ''}) %>
<input type="hidden" id="currect_opened_req_id" value="" name="FinalizeDeal[title]"/>
<select name="meeting-id">
<option value="1">Meeting 1</option>
<option value="2">Meeting 2</option>
</select>
<label for="details-lbms">Details</label>
<textarea id="details-lbms" name="FinalizeDeal[description]"></textarea>
<button class="button tiny">
Submit
</button>
</form>
<a class="close-reveal-modal">×</a>
</div>
Please tell me what am I doing wrong. I am also posting a link to the screenshot of the error
http://tinypic.com/r/n6t8w2/8
http://tinypic.com/r/33kdq1k/8
The code is complaining because you are requiring the :finalizedeal parameter (but apparently you are not passing it along) by adding this .require(:finalizedeal) to this code:
def finalizedRequest_params
params.require(:finalizedeal).permit(:title , :description)
end
So one solution would be to simply remove the require part. Like so:
params.permit(:title , :description)
#require source
Ensures that a parameter is present.
I am doing a before_validation as follows:
event.rb
attr_accessor :start_date
attr_accessible :start_time #recorded in database as a datetime
before_validation :build_start_time
...
def build_start_time
begin
self.start_time = DateTime.parse(start_date)
rescue
errors.add(:start_date, "invalid date")
return false
end
end
and the controller looks like:
def create
#event = events.build(params[:event])
if #event.save
# some other method calls
redirect_to #event
else
redirect_to :root
end
end
start_date is being set by a <%= f.text_field :start_date %> call in a form view, and when I check the params it is being passed to the 'Create' method of the model controller correctly, but in the build_start_time method it is nil, so self.start_time is not being set. Can you explain why it would be nil and what the solution would be? I also tried referring to it as self.start_date but that didn't make a difference.
Thanks
Have you tried making start_date also accessible?
Either you call attr_accessible with start_date so build() can actually set it, or you can change your controller to:
def create
#event = events.build(params[:event])
#event.start_date = params[:event][:start_date]
if #event.save
# some other method calls
redirect_to #event
else
redirect_to :root
end
end
tente assim.
#app/models/adm/video.rb
class Adm::Video < ActiveRecord::Base
validates :titulo, :url_codigo, presence: true
before_validation(on: [ :create, :update ]) do
self.url_codigo = parse_youtube(url_codigo) #url_codigo = params[:adm_video][:url_codigo]
end
private
# pega só o codigo do link youtube para inserir no banco
def parse_youtube(url)
if !url.blank?
regex = /(?:.be\/|\/watch\?v=|\/(?=p\/))([\w\/\-]+)/
return url.match(regex)[1] # https://www.youtube.com/watch?v=iX_rKHnKJSg = iX_rKHnKJSg
end
end
end
grava no banco de dados sò código do video = iX_rKHnKJSg = https://www.youtube.com/watch?v=iX_rKHnKJSg = iX_rKHnKJSg.
records in the database sò code iX_rKHnKJSg video = # = https://www.youtube.com/watch?v=iX_rKHnKJSg iX_rKHnKJSg