I am trying to find a solution the above problem.
Basically, I have a model 'Job', which has and belongs to many contacts and locations. When a user begins creating a new job, they should be able to begin adding locations and contacts to the new record. The problem is when I try save the record. How can a user associate location and contact records to a job record that doesn't yet have an ID? The error message I get on the create action is this,
For every contact I try to add I get a
Validation failed: Job contacts is invalid
Which i guess comes from the fact a Job ID doesn't exist at the time of assignment.
The parameters that come through to the controller are all within the job_params, which is how I want them to be received. This is aided with SimpleForm, which has the handy 'association' method for habtm records. If possible I would like to keep everything within a form object using simple form (not using field_tags etc). So for example the contact field looks like this.
=f.association :contacts, collection: job.client.contacts, as: :check_boxes
So what are my options? Is there something I can do differently?
I had considered the following:
Creating a record in the new action and setting it with a flag to state its invalidity until the necessary fields have been populated. At which point it can become a 'proper' record, but this feels as though it has the potential to get quite messy.
Using STI to start a dummy record?
Maybe I'm way off piste with all this, but even some direction would be greatly appreciated.
Assign the users id to the job. Then, when looking for jobs for the user do
jobs = Job.where("user_id = ?", user.id)
Related
I've learned a lot in Access over the last month or so but am now have trouble resolving an issue that I don't know how to approach. I'm sure there's a simple solution but I need help being pointed in the right direction. Here's the background:
This problem deals with three forms:
frmProject - Lists project details it has a
subfrmMilestones - Milestone details
frmProjMsgBox - Collects info to pass to Project table
I have it set that when I click OK on ProjectMsgBox it passes the information to the Project form and starts the creation of a new record.
tblProject stores all details related to projects
tblMilestones stores all details on milestones, contains key for tblProject
tblMilestones_Inf stores a list of common milestones based on project type, has key for tblProjectType, which is on tblProject
My Problem -
When I click okay on the ProjectMsgBox form, I would like it to also look up milestones from tblMilestones_Inf and insert into tblMilestones. I also need to assign the Project_ID that on the form to the creates. What is the best way to go about this?
I've tried a few things in VBA but haven't had success. I can create a query that pulls the milestones in but don't know how to update the milestone table with the relationship to the project table.
I can provide more details but wasn't sure what is helpful and what is not. I'm more or less looking for a resource (or keywords to search) so I can figure this out on my own
Thank you!
UPDATE:
tblProject has 1 to many relationship with tblMilestones
tblProjectType has 1 to many relationship with tblMilestones_Inf
Once I hit okay on the frmProjMsgBox it fills out text boxes that have controls on frmProject to create the parent record (i think that's the term) in tblProject. This works well. I would like access to go out to the tblMilestones_Inf and match the project type (child record?). It would then add 4-5 records based on matching ProjectType on the Milestone_Inf table. I don't want code, but maybe actions/keywords to lookup so I can figure this out on my own. I'll post some of my code later that tries to achieve this.
You might want to look into Query Defs, you can use those to change the SQL statement of your queries from VBA. So if you have something like:
MyQryDef.SQL = "SELECT * FROM MyTable WHERE MyIndex = " & MyControl.Value & ";"
and your control value is set to 5, you then use the execute statement and your Query SQL will then read:
SELECT * FROM MyTable WHERE MyIndex = 5;
There's a few more lines you will have to look up to make this work, but this is a very basic example.
In my Firebase database, I have a data structure similar to this:
The post ID (1a3b3c4d5e) is generated by the ChildByAutoId() function.
The user ID (fn394nf9u3) is the UID of the user.
In my app, I have a UILabel (author) and I would like to update it with the 'full name' of the user who created the post.
Since I have a reference to the post ID in the users part of the database, I assume there must be some code (if statement?) to check if the value exists and if so, update the label.
Can you help with that?
While it is possible to do the query (ref.child("Users").queryOrdered(byChild: "Posts/1a3b3c4d5e").queryEqual(toValue:true)), you will need to have an index on each specific user's posts to allow this query to run efficiently. This is not a feasible strategy.
As usual when working with NoSQL databases: if you need to do something that your current data model doesn't allow, change your data model to allow the use-case.
In this case that can either be adding the UID of the user to each post, or alternative add the user name to each post (as Andre suggests) and determining if/how you deal with user name changes.
Having such relational data in both directions to allow efficient lookups in both directions is very common in NoSQL database such as Firebase and Firestore. In fact I wrote a separate answer about dealing with many-to-many relations.
If you can change the structure then that is very good because I don't think you are maintaining proper structure for database.
You should take one more key name createdBy inside the Post node so actully structure would be
{description:"Thus the post is here", title:"Hello User", createdBy:"Javed Multani"}
Once you do this, It will dam easy to get detail of user.
OR
Unethical solution,
You can achieve this thing like while you are going to show Post from post node of firabase. Definitely you'll get the auto generated postid like:
1a3b3c4d5e
now first you should first get only posts then inside the successfully getting data and parsing you have to get users and find inside the user by putting the codition like postId == UserPostId if match found take fullname value from there.
I am trying to make a backup table of users, called archived users. It creates the ArchivedUser by taking a hash of the current users attributes (self) and merging in the self.id as the user_id.
When a user is reinstated, their record as an ArchivedUser still remains in the ArchivedUser table. If the user gets deleted a second time, it should update any attributes that have changed.
Currently, it throws a validation error:
Validation failed: User has already been taken, as the self.id already exists in the ArchivedUser table.
What is a better way to handle an object where you update an existing object if possible, or create a new record if it doesn't exist. I am using Rails 4 and have tried find_or_create_by but it throws an error
Mysql2::Error: Unknown column 'device_details.device_app_version'
which is odd, as that column exists in both tables and doesn't get modified.
User Delete Method
# creates ArchivedUser with the exact attributes of the User
# object and merges self.id to fill user_id on ArchivedUser
if ArchivedUser.create!(
self.attributes.merge(user_id: self.id)
)
Thanks for taking a peek!
If your archived_users table is truly acting as a backup for users and not adding any additional functionality, I would ditch the ArchiveUser model and simply add an archived boolean on the User model to tell whether or not the user is archived.
That way you don't have to deal with moving an object to another table and hooking into a delete callback.
However, if your ArchiveUser model does offer some different functionality compared to User, another option would be to use single table inheritence to differentiate the type of user. In this case, you could have User govern all users, and then distinguish between a user being, for example, an ActiveUser or an ArchivedUser.
This takes more setup and can be a bit confusing if you haven't worked with STI, but it can be useful when two similar models need to differ only slightly.
That being said, if you want to keep your current setup, I believe there are a few issues I see with your code:
If you are going to create an object from an existing object, it's good practice to duplicate the object (dup). That way the id won't be automatically set and can be auto-incremented.
If you truly have deleted the User record from the database, there's no reason to store a reference to its id because it's gone. But if you aren't actually deleting the record, you should definitely just use a boolean attribute to determine whether or not the user is active or archived.
I don't have enough context here as to why find_or_create_by isn't working, but if it were the case, then I would keep it as simple as possible. Don't use all the attributes, but just the consistent ones (like id) that you know will return the proper result.
if ArchivedUser.create! # ... is problematic. The bang after create (i.e. create!) will throw an error if the record could not be created, making the if pointless. So, either use if if you don't want errors thrown and want to handle the condition in which the record was not created. Or use create! without if if you do want to throw an error.
Is it possible to eager load a specific entry from the user table, as well as all associated tables attached via belong_to.
For example, I have users table with accounts and patients tables, that both belong_to :user. If I wanted to grab a specific User table entry and eager_load the associated tables, akin to something like this:
user = User.find_by_email("testemail#here.com").eager_load(:accounts, :patients)
How can I do it ?
You were close. Try putting the associations in an array within the eager_load call as shown below:
user = User.includes([:accounts, :patients]).find_by(email: "testemail#here.com")
Now that you have included the associated tables and then found your user you can call any attributes from those other tables on the user without firing another query from the database. For example once that is run you can do:
all_user_accounts = user.accounts
This will not fire a query in the database but instead be loaded from memory.
If you use #eager_load you are doing one query whereas includes will do it in one or two depending on what it deems necessary. So what is #includes for? It decides for you which way it is going to be. You let Rails handle that decision.
Check this guide for great information on includes/eager_load/preload in rails:
http://blog.arkency.com/2013/12/rails4-preloading/
The Setup:
I have a large form with many fields that are collected to update a Product object. So in the ASPX page the user changes the fields that need updating and they hit submit. In the code behind I do something like this;
Dim p as New MyCompany.Product()
p = p.GetProductById(ProductID)
I extend the Product partial class of Linq to SQL to add this method (GetProductById) to the object
p.Name = txtName.Text
p.SKU = txtSKU.Text
p.Price = txtPrice.Text
...
p.Update()
This is an Update method in the extended Product partial class. I update the database, send emails and update history tables so i want this method to do all those things.
There are 50 more fields for the project so obviously it would be ridiculous to have a method that collects all 50 fields (and I don't want to go that route anyway bc it's harder to debug IMO)
The Problem:
If I get the Product via Linq to SQL using a DataContext then I can never update it again because it errors about not being able to attach and entity that's already attached to another DataContext.
The Question:
SO if I get an object through a method in my BLL, update it in the ASPX page and then try to send the updates through the BLL again to update the database, how should I go about doing this?
Regardless of LINQ-to-SQL or not, here's what I do. Upon submission, I search for the item (it should be quick if it is a single item using the PK), my DAL returns a data object, and I use reflection to map each element in the page with corresponding properties in the data object. My DAL only updates items that changed.
I think what you have to do is the same, gathering all values and submitting them. If LinqToSql is not smart enough to determine what changed then it may not be the best alternative.