Need Help passing an instance variable to another method for insert in ruby on rails 4 - variables

I am new to ROR and spent most of the day trying to get this to work. I have tried using the before_filter and I cannot get my object to insert in another method.
The view is index, a file is selected in the view and then the button to validate file is clicked which calls a method 'evaluate_media' in this method, I look up values based on the file path and name selected and I can successfully insert the record with all the values in this method. The problem is I don't want an automatic save. When the 'evaluate_media' method is done it displays back with either a save button or an update button based on if the file submitted already exists in the database. Then the user can choose to save/update the record or now. This button calls the 'save_file' action. The problem is all the information save in 'evaluate_media' action for the file is not accessible to save_file or update_file actions. I believe session variables might be my answer but I could not find any good examples to get it setup correctly and working in my application. Can someone please tell me and show me the proper code to pass the value from 'evaluate_media' action to save_file or update_file actions?
Here is the code where I assign the values for a new record in my evaluaate_media method:
if #file_exists_flag == 'NEW'
# Assign Parameter values for new save
#file_alias_tfile = FileAliasTfile.new( {:src_location => #radio_button_value, :directory => #dir_path_choice, :full_path => #selected_filepath, :full_filename => #filepath, :file_ext => '',
:assigned_status => 'Unassigned', :file_status => 'Saved', :alias_code => #file_alias.to_s, :validate_status => #file_status.to_s, :error_msg => #file_msg.to_s,
:video_alias_match => #msg_dtl1.to_s, :audio_alias_match => #msg_dtl2.to_s, :video_format => #video_format.to_s, :video_bitrate => #video_bitrate.to_s,
:video_width => #video_width.to_s,
:video_height => #video_height.to_s, :video_framerate => #video_framerate.to_s, :video_aspect_ratio => #video_aspectratio.to_s, :video_scan_type => #video_scantype.to_s,
:video_scan_order => #video_scanorder.to_s, :video_alias_code => '', :audio_alias_code => '', :bus_prod_initiative_id => 0, :status => 'Active', :start_date => DateTime.now.to_date,
:end_date => '', :deleted_b => 0, :created_by => 'admin', :updated_by => 'admin'} )
end
Then if the user clicks the save, the save_file method is called and here is the code to save the
values from evaluate_media into the database:
def save_file
#file_alias_tfile = FileAliasTfile.create(#file_alias_tfile)
#file_alias_tfile.save
end
I figure the update will be the same as the save so I only included one case here.
Your help is appreciated. Thank you!

First of all,
def save_file
#file_alias_tfile = FileAliasTfile.create(#file_alias_tfile)
#file_alias_tfile.save
end
ModelName.create() is equivalent to ModelName.new(....).save. So the second line should be deleted.
You could do this:
if #file_exists_flag == 'NEW'
session[:my_file] = FileAliasTfile.new( .... )
def save_file
session[:my_file].save
end
However, generally it's not recommended to save model objects in the session. Instead, you should save the object in the database; then save the id of the object in the session. I know, "But I don't want to save the object in the database until the user confirms". Have you ever heard of the destroy() method? For instance,
FileAlias.destroy(session[:file_id])
which deletes the record in the file_aliases table with an id equal to session[:file_id].
When the 'evaluate_media' method is done it displays back with either
a save button or an update button based on if the file submitted
already exists in the database.
So, create() the record (remember that saves the record), and if the user clicks the save button, do nothing. If the user clicks the update button, then delete the record from the database and delete the id from the session. For example:
if #file_exists_flag == 'NEW'
my_file = FileAlias.create( .... )
session[:file_id] = my_file.id
def save_file
#render some page
end
def update_file
my_file = FileAlias.destroy(session[:id])
session.delete[:file_id]
#Do something with my_file?
end

Related

How to add New Attachment field Orange Hrm leaveplugin

Thanks In advance
I want Add New Attachment Field before the comment field in leaveplugin In apply leave form How i do please tell step vise
Add this in
getFormWidgets()-
'attach' => new sfWidgetFormInputFileEditable(array('edit_mode' => false,'with_delete' => false, 'file_src' => ''))
Add following code in
getFormValidators() function -
'attach' => new sfValidatorFile(array('required' => false, 'max_size' => 1024000, 'validated_file_class' => 'orangehrmValidatedFile'))
In action class, bind that form with $request->getFiles().
How to add fields in candidate form
First add all threee field in #_job_candidate table
orangehrm\symfony\plugins\orangehrmRecruitmentPlugin\lib\form\AddCandidateForm.php
orangehrm\symfony\plugins\orangehrmRecruitmentPlugin\modules\recruitment\templates\addCandidateSuccess.php
orangehrm\symfony\lib\model\doctrine\orangehrmRecruitmentPlugin\base\BaseJobCandidate.class.php
but all data is not Inserted in database

Magento bundle products - selection_id cannot be null?

I am trying to create a bundled product programmatically, and setting the options via this:
$new_options[$count] = array(
'required' => 0,
'position' => 1,
'parent_id' => $parentProduct->getId(),
'type' => 'select',
'title' => $product->getName(),
'default_title' => $product->getName()
);
$new_selections[$count] = array(array(
'product_id' => $product->getEntityId(),
'selection_qty' => $child['qty'],
'selection_can_change_qty' => 0,
'position' => 0,
'is_default' => 1,
'selection_price_type' => 0,
'selection_price_value' => 0.0
));
...
$parentProduct->setBundleOptionsData($new_options);
$parentProduct->setBundleSelectionsData($new_selections);
Which looks correct (as described in https://stackoverflow.com/a/4415800/494643). However, it is not working - I get an SQL exception complaining that Column 'selection_id' cannot be null'. How do I get around this? The selection id is an auto_increment column, so I can't get it until it is created, but it looks like it cannot be created?
The solution lies in the _beforeSave function of the Mage_Bundle_Model_Selection model.
This causes it to attempt to write the selection_id to the catalog_product_bundle_selection_price table, before it has saved the selection object - and therefore before it has generated a selection_id. The answer therefore is to force it to generate an id before it saves, so looking again at the _beforeSave function, we can see that it only saves the price if the store is not 0.
Specifically, this part:
$storeId = Mage::registry('product')->getStoreId();
if (!Mage::helper('catalog')->isPriceGlobal() && $storeId) {
which means that if we set the store id of the registry product to 0 first, we can cause it to save the selection, without saving the price. We would then need to reset the store to the previous value, and save again, to record the price - although only after having reloaded the object to get the newly generated selection id.

cakephp url not retrieving data

hi all when clicking the link on my page its not carrying the id from the template when going to the view page, so when the sql queries the database it is querying this
SELECT `Field`.`name`
FROM `pra`.`fields` AS `Field`
LEFT JOIN `pra`.`templates` AS `Template` ON (
`Field`.`template_id` = `Template`.`id`)
WHERE `template`.`id` IS NULL
the database says id should be = 2
here is the code for the view function
$fields = $this->Field->find('all',
array('fields'=>array('name','template_id'),
'conditions' => array('template_id' => $this->Auth->user('template.id'))));
$this->set('field', $fields);
updated code, the template_id still equals null
when hardcoded it works correctly, there is a problem with this line $this->Auth->user
You can try with the following code:
$fields = $this->Field->find('all',
array('fields'=>array('name'),
'conditions' => array('Field.template_id' => $this->Auth->user('template_id'))
)
);
$this->set('field', $fields);
Please be sure there must have any template_id value should be there for the current logged in user.
Kindly ask if it not worked for you.
Check the result of the find call, by doing a debug:
debug($fields);
This will show you the returned data from the query. You can add this to the end of your action method.
If the results are empty, double check the values that are stored in the session Auth key. You can do this by dumping out the session with debug($_SESSION) or use the CakePHP DebugKit. The Debug Kit offers you a small toolbar at the top right of the screen and lets you view session information and such.
function view($name){
$this->set('title_for_layout', 'Create Template');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
$fields = $this->Template->Field->find('list',array(
'fields'=> array('name'),
'conditions' => array(
'template_id'=> $name)));
$this->set('field', $fields);
}
it wasn't passing the param's value

Configuring rails database query so that blank string parameters are ignored

I'm making a rails application so that users can search a database of midi records and find midi files that correspond to the attributes that I've given them.
For example, a user might enter data into an html form for a midi file with name = "blah" composer= "buh" and difficulty = "insane".
This is all fine and well, except that I would like when the user enters no data for a field, that field is ignored when doing the select statement on the database.
Right now this is what my select statement looks like:
#midis=Midi.where(:name => params[:midi][:name],
:style => params[:midi][:style],
:numparts => params[:midi][:numparts],
:composer=> params[:midi][:composer],
:difficulty => params[:midi[:difficulty])
This works as expected, but if for example he/she leaves :composer blank, the composer field should not considered at all. This is probably a simple syntax thing but i wasn't able to find any pages on it.
Thanks very much!
Not sure if Arel supports that directly, but you could always do something like:
conditions = {
:name => params[:midi][:name],
:style => params[:midi][:style],
:numparts => params[:midi][:numparts],
:composer=> params[:midi][:composer],
:difficulty => params[:midi[:difficulty]
}
#midis=Midi.where(conditions.select{|k,v| v.present?})
Try this:
# Select the key/value pairs which are actually set and then convert the array back to Hash
c = Hash[{
:name => params[:midi][:name],
:style => params[:midi][:style],
:numparts => params[:midi][:numparts],
:composer => params[:midi][:composer],
:difficulty => params[:midi][:difficulty]
}.select{|k, v| v.present?}]
Midi.where(c)

Rails 3.1 create record rather than update?

I have the following Nokogiri rake task in my Rails (3.1) application:
desc "Import incoming calls"
task :fetch_incomingcalls => :environment do
# Logs into manage.dial9.co.uk and retrieved list of incoming calls.
require 'rubygems'
require 'mechanize'
require 'logger'
# Create a new mechanize object
agent = Mechanize.new
# Load the dial9 website
page = agent.get("https://manage.dial9.co.uk/login")
# Select the first form
form = agent.page.forms.first
form.username = 'username
form.password = 'password'
# Submit the form
page = form.submit form.buttons.first
# Click on link called Call Logs
page = agent.page.link_with(:text => "Call Logs").click
# Click on link called Incoming Calls
page = agent.page.link_with(:text => "Incoming Calls").click
# Output results to file
# output = File.open("output.html", "w") { |file| file << page.search("tbody td").text.strip }
# Add each row to a new call record
page = agent.page.search("table tbody tr").each do |row|
next if (!row.at('td'))
time, source, destination, duration = row.search('td').map{ |td| td.text.strip }
Call.create!(:time => time, :source => source, :destination => destination, :duration => duration)
end
end
The time value is the first row in the table and is unique per call (as we can only receive one call at a time).
What I would like to do is use the time value as the unique identifier for my call logs.
So when scraping the screen, it will "update" the existing calls (which won't change but it's the only way I can think of only importing new calls).
If I set it to:
Call.find_all_by_time(nil).each do |call|
and then:
call.update_attribute(:time, time)
Then it will update the existing records, but I want it to import records that aren't already in our database - based on the time value.
Any help is appreciated!
Do you mean this?
# Add each row to a new call record
page = agent.page.search("table tbody tr").each do |row|
next if (!row.at('td'))
time, source, destination, duration = row.search('td').map{ |td| td.text.strip }
call = Call.find_or_create_by_time(time)
call.update_attributes({:time => time, :source => source, :destination => destination, :duration => duration})
end