In CREATE, init with params does fill all attributes - postgresql

I am using RoR 3.1 + Postgres on MacOSX
In my create function I have this:
def create
#power_plant_substrate = PowerPlantSubstrate.new(params[:power_plant_substrate]) <= 1
#trade = params[:power_plant_substrate][:trade]
respond_to do |format|
if #power_plant_substrate.save
...
end
(1) should instantiate a new object with params[:power_plant_substrate]
THE PROBLEM:
Right after the creation of my new object #power_plant_substrate some of the attribute are available.
if I check params[:power_plant_substrate] value (trace to console) I can verify that all fields were passed correctly:
{"power_plant_id"=>"161", "substrate_id"=>"213", "quantity"=>"1", "periodicity"=>"yearly", "trade"=>"wanted", "price_per_unit"=>"0.00", "total_price"=>"0.00", "currency"=>"USD", "address"=>", Reserved", "transport"=>"pickup_only", "description"=>"afewrqe", "latitude"=>"", "longitude"=>""}
However I checked my object right after saving (#power_plant_substrate.save). "trade" attribute is not assigned anymore.
I tried accessing the same attributes in the model in a method that I call after_create, and same problem.
However, the record is available with all fields correctly assigned in the database.
WHY #power_plant_substrate object doesn't appear "fully" assigned after saving?
Hope you can help.

My guess is that there is a list of attr_accessible in PowerPlantSubstrate model. check if currency and trade are added in that list. If not, then add those.
attr_accessible :currency, :trade, . . .
Making a few attributes alone as attr_accessible will make it impossible to mass assign other variables. That is why individual assignment worked
If there is not list, try adding
attr_accessible nil
and see if that works

Related

Lookup Edit binding

I have a model written using Entity Framework Code First called Project.
In my UI, there is a page called ProjectEdit as shown in the image below. As seen in the image below, Customer and BOMs are Lookup Edit.
I'm trying to load Customer and BOMs to Lookup Edit but it's not working. Below is my code.
//New
if (entity == null)
{
Entity = new Project();
}
//Edit
else
{
ProjectCodeTextEdit.DataBindings.Add("EditValue", entity, "ProjectCode");
DescriptionTextEdit.DataBindings.Add("EditValue", entity, "Description");
CustomerLookUpEdit.DataBindings.Add("EditValue", entity, "CustomerId");
BOMsLookUpEdit.DataBindings.Add("EditValue", entity, "BOMs");
}
Below is my LookUpEdit Properties.
Generally LookUpEdit object's data binding is not implemented the same way as a TextEdit object's. While in TextEdits's case you just need to assign the variable value to EditValue property (I suppose your TextEdits binding work fine, isn't it?), with LookUp Edit you should assign variables to ValueMember and a DisplayMember properties of the object. That is why we usually display data rows with LookUpEdit objects, where ValueMember is the identification field of the row and DisplayMember is the field of the row whose value you wish to be displayed.
In your case you should be more clear about what you wish to display in your lookupedits. Each Project instance has one Customer property and many BOMs, right? So CustomerLookUpEdit will show one record and BOMsLookUpEdit a list of values according to the Project object that was chosen for edit, correct? I suppose that both your Customer and BOM classes have some kind of ID property and description property of their own. In this case you should bind these values to the LookUpEdits. eg. in your initialization function code add these lines
CustomerLookUpEdit.Properties.DataSource = entity.Customer;
CustomerLookUpEdit.Properties.ValueMember = "someCustomerIDpropertyName" ;
CustomerLookUpEdit.Properties.DisplayMember = "someCustomerDescriptionpropertyName";
BOMsLookUpEdit.Properties.DataSource = entity.BOMs;
BOMsLookUpEdit.Properties.ValueMember = "someBOMIDpropertyName" ;
BOMsLookUpEdit.Properties.DisplayMember = "someBOMDescriptionpropertyName" ;
You can read more in this topic https://documentation.devexpress.com/#WindowsForms/clsDevExpressXtraEditorsLookUpEdittopic
When we are adding entities to a List, we have to take care of our DataSource if is a DBContext or a DBSet, each one has implications in the compiler, that was your case, in this case you had to especify your DataSource like a DBSet and get the Entities
Add<TEntity>(TEntity entity)
The type parameter omitted is posible because the compiler will infer it.

Passing arguments to Access Forms created with 'New'

I have a form called 'detail' which shows a detailed view of a selected record. The record is selected from a different form called 'search'. Because I want to be able to open multiple instances of 'detail', each showing details of a different record, I used the following code:
Public detailCollection As New Collection
Function openDetail(patID As Integer, pName As String)
'Purpose: Open an independent instance of form
Dim frm As Form
Debug.Print "ID: " & patID
'Open a new instance, show it, and set a caption.
Set frm = New Form_detail
frm.Visible = True
frm.Caption = pName
detailCollection.Add Item:=frm, Key:=CStr(frm.Hwnd)
Set frm = Nothing
End Function
PatID is the Primary Key of the record I wish to show in this new instance of 'detail.' The debug print line prints out the correct PatID, so i have it available. How do I pass it to this new instance of the form?
I tried to set the OpenArgs of the new form, but I get an error stating that OpenArgs is read only. After researching, OpenArgs can only be set by DoCmd (which won't work, because then I don't get independent instances of the form). I can find no documentation on the allowable parameters when creating a Form object. Apparently, Microsoft doesn't consider a Constructor to be a Method, at least according to the docs. How should I handle this? (plz don't tell me to set it to an invisible text box or something) Thanks guys, you guys are the best on the net at answering these questions for me. I love you all!
Source Code for the multi-instance form taken from: http://allenbrowne.com/ser-35.html
Inside your Form_detail, create a custom property.
Private mItemId As Long
Property Let ItemID(value as Long)
mItemId = value
' some code to re query Me
End Property
Property Get ItemId() As Long
ItemId = mItemId
End Property
Then, in the code that creates the form, you can do this.
Set frm = New Form_detail
frm.ItemId = patId
frm.Visible = True
frm.Caption = pName
This will allow you to pass an ID to the new form instance, and ensure it gets requeried before making it visible. No need to load all of the results every time if you're always opening the form by Newing it. You let the property load the data instead of the traditional Form_Load event.
This works because Access Form modules are nothing more than glorified classes. Hope this helps.
You could try applying a filter:
frm.Filter = "[ID] = " & patID
frm.FilterOn = True
The Record Source of the Detail form will need to be set to the table to which the ID belongs.
UPDATE
As you requested, here is the code to set the RecordSource:
frm.RecordSource = "select * from TableName where [ID] = " & patID
This is probably cleaner than using a filter given that a user can remove the filter (depending on the type of form).

Symfony2 form validation of Doctrine2 object: accessing previous values on updates

I've written a class validator as a service and passed the doctrine entity manager to this validator. At this point everything works fine.
But now I need the unchanged object of $entry which is been updated in the form - or at least the previous values. I've tried some approaches, but did not succeed:
public function isValid($entry, Constraint $constraint)
{
$oldEntry = $this->em->getRepository('SomeBundle:Entry')->findOneBy(array('id' => $entry->getId()));
Doctrine fetches the same (changed) object as expected. But trying to refresh the object will reset both versions of the object:
$newEntry = clone $entry;
$this->em->detach($newEntry);
$this->em->refresh($entry);
$hoursOfOldEntry = $entry->calculateHours();
$this->em->merge($newEntry);
Another option could be to save the values of the object as array, refresh the object and reassign the saved values again after working on the original values. But this does not seem to be the best way, especially if the are many relations. I don't wont to touch the object within a validator, I just need the previous values!
Another approach could be using Doctrine\ORM\UnitOfWork#recomputeSingleEntityChangeSet(Doctrine\ORM\ClassMetadata $meta, $entity). But I don't think it's a good idea to use internal doctrine methods in a validator!
So how do I get the original object or the change set in a class validator?
This won't get you the original entity, but should get you a key/value array of the original fields:
$uow = $em->getUnitOfWork();
$originalData = $uow->getOriginalEntityData($entry);
http://www.doctrine-project.org/api/orm/2.0/source-class-Doctrine.ORM.UnitOfWork.html#2210

How to specify computed property dependency in EmberJS on an array of objects that contain another array

I am using EmberJS and I am trying to setup the dependency on a computed property. A visitor can contain multiple tickets (an array), and I have access to an object containing an array of visitors. This is my computed property. How can the property be recomputed when a ticket is added to any of the visitors in the visitors array?
App.AttendanceController = App.SlideBaseController.extend
eligibleVisitors:
(->
return #getElegibleVisitors()
).property('App.state.session.visitors.#each.type')
allEligibleVisitorsAttending:
(->
return _.all #getElegibleVisitors(), (visitor)->
return visitor.tickets.length > 0 and _.any visitor.tickets, (ticket)->
return ticket.EventID is content.Event.ID
).property('App.state.session.visitors.tickets')
getElegibleVisitors:->
return _.filter App.state.session.visitors, (visitor)->
return visitor.type isnt App.VisitorTypes['Infant']
Something like this should work:
.property('App.state.session.visitors.#each.tickets.#each')
Updates when any ticket is added to any visitor.
AFAIK this is not possible right now and won't be for Ember 1.0. See here: https://github.com/emberjs/ember.js/issues/541
Nested #each properties don't trigger observers correctly.
I faced a similar problem (nested tree structure) -- I got around it by having each child node have a reference property to the parent node, and then adding
Node = Ember.Object.extend
nodeParent: null # to point at parent
nodeChanged: (->
#get('nodeParent')?.notifyPropertyChange 'notifier'
).observes 'various', 'properties
I used 'notifier' as a general key that other properties on the parent can bind to; when things in the child change, it causes a property change on the parent.notifier, which will in turn trigger other properties you want.
This is a hacky work around. Plus side is that it works, downside is you have to keep track of the child-parent relationship; i.e., for you, each Ticket needs to a reference to its Visitor

Symfony: Model Translation + Nested Set

I'm using Symfony 1.2 with Doctrine. I have a Place model with translations in two languages. This Place model has also a nested set behaviour.
I'm having problems now creating a new place that belongs to another node. I've tried two options but both of them fail:
1 option
$this->mergeForm(new PlaceTranslationForm($this->object->Translation[$lang->getCurrentCulture()]));
If I merge the form, what happens is that the value of the place_id field id an array. I suppose is because it is waiting a real object with an id. If I try to set place_id='' there is another error.
2 option
$this->mergeI18n(array($lang->getCurrentCulture()));
public function mergeI18n($cultures, $decorator = null)
{
if (!$this->isI18n())
{
throw new sfException(sprintf('The model "%s" is not internationalized.', $this->getModelName()));
}
$class = $this->getI18nFormClass();
foreach ($cultures as $culture)
{
$i18nObject = $this->object->Translation[$culture];
$i18n = new $class($i18nObject);
unset($i18n['id']);
$i18n->widgetSchema['lang'] = new sfWidgetFormInputHidden();
$this->mergeForm($i18n); // pass $culture too
}
}
Now the error is:
Couldn't hydrate. Found non-unique key mapping named 'lang'.
Looking at the sql, the id is not defined; so it can't be a duplicate record (I have a unique key (id, lang))
Any idea of what can be happening?
thanks!
It looks like the issues you are having are related to embedding forms within each other, which can be tricky. You will likely need to do things in the updateObject/bind methods of the parent form to get it to pass its values correctly to its child forms.
This article is worth a read:
http://www.blogs.uni-osnabrueck.de/rotapken/2009/03/13/symfony-merge-embedded-form/comment-page-1/
It gives some good info on how embedding (and mergeing) forms work. The technique the article uses will probably work for you, but I've not used I18n in sf before, so it may well be that there is a more elegant solution built in?