Search Results

Search found 676 results on 28 pages for 'polymorphic associations'.

Page 11/28 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Get parent attribute within new child form?

    - by dannymcc
    I have a simple Rails 3 application and I am trying to create a new record that belongs to it's owner. It's working by passing the id to a hidden field in the new form of the child record. This works well and once the new child form submitted it correctly gets associated in the child/parent relationship. What I am trying to do, is lookup values form the parent within the new child form. The problem is that the child relationship is not yet created. Is there anyway I can use a .where lookup in the view? Or, is there a better way of doing this? At the moment I am passing the animal_id though to the new Claim form and it's inserted into a hidden field labelled animal_id. What I am trying to do: <%= @animal.where(:animal_id => params[:animal_id]).id %> The above would ideally get the animal ID from the soon-to-be-associated animal. Is there any sort of before_filter or anything that could take the passed params from the URL and temporarily create the relationship just for the new form view and then permanently create the relationship once the form is submitted? I've tried adding the following to my Claims controller and then called @animal.AnimalName in the view but I get NoMethodError: before_filter :find_animal protected def find_animal if params[:animal_id] Animal.find(params[:animal_id]) end end The URL of the new claim is correctly showing the animal ID so I'm not sure why it's not finding it: http://localhost:3000/claims/new?animal_id=1 The model relations are as follows: animal has_many claims animal has_one exclusion claim has_one animal exception has_one animal

    Read the article

  • ActiveRecord find all parents that have associated children

    - by brad
    I don't know why I can't figure this out, I think it should be fairly simple. I have two models (see below). I'm trying to come up with a named scope for SupplierCategory that would find all SupplierCategory(s) (including :suppliers) who's associated Supplier(s) are not empty. I tried a straight up join, named_scope :with_suppliers, :joins => :suppliers which gives me only categories with suppliers, but it gives me each category listed separately, so if a category has 2 suppliers, i get the category twice in the returned array: Currently I'm using: named_scope :with_suppliers, :include => :suppliers and then in my view I'm using: <%= render :partial => 'category', :collection => @categories.find_all{|c| !c.suppliers.empty? } %> Not exactly eloquent but illustrates what I'm trying to achieve. Class Definitions class SupplierCategory < AR has_many :suppliers, :order => "name" end class Supplier < AR belongs_to :supplier end

    Read the article

  • Can't grab foreign key during after_create callback because it doesn't exist yet!

    - by Randy
    I have some models all linked together in memory (parent:child:child:child) and saved at the same time by saving the top-most parent. This works fine. I'd like to tap into the after_create callback of one of the children to populate a changelog table. One of the attributes I need to copy/push into the changelog table is the child's foreign_key to it's direct parent, but it doesn't exist at the time after_create fires!?! Without the after_create callback, I can look in the log and see that the child is being saved before it's parent (foreign key blank) then the parent is inserted... then the child is updated with the id from the parent. The child's after_create is firing at the right time, but it happens before Rails has had a chance to update the child with the foreign_key. Is there any way to force Rails to save such a linkage of models in a certain order? ie.parent, then child (parent foreign_key exists), then that child's child (again, foreign_key is accessible) etc. ?? If not, how would I have my routine fire after a record is created AND get the foreign_key? Seems a callback like this would be helpful: after_create_with_foreign_keys

    Read the article

  • ordering a collection by an association's property

    - by neiled
    class Person belongs_to :team class Status #has last_updated property class Team has_many :members, :class => "Person" Ok, so I have a Team class which has many People in it and each of those people has a status and each status has a last_updated property. I'm currently rendering a partial with a collection similar to: =render :partial => "user", :collection => current_user.team.members Now how do I go about sorting the collection by the last_updated property of the Status class? Thanks in advance! p.s. I've just written the ruby code from memory, it's just an example, it's not meant to compile but I hope you get the idea!

    Read the article

  • CPU emulator on C for assembler

    - by krlzx00
    Hi, there. I have a problem. I´m working on a little aplication of security, but i recived an array that means a bytes, and that bytes can be interpreted as a assembler code, so my cuestion is.... some one knows a library that a i can use on my aplication that can execute this bytes and show what it do, or something like that?

    Read the article

  • Rails find all with association

    - by aaronrussell
    I have what I think is a very simple problem (famous last words)... I have a Category model that has_and_belongs_to_many Events. I want to construct a simple and efficient query that finds all categories that have 1 or more events. (using Rails 3) I'm sure I'm having a dumb moment here - any help appreciated :)

    Read the article

  • Can I Have Polymorphic Containers With Value Semantics in C++11?

    - by John Dibling
    This is a sequel to a related post which asked the eternal question: Can I have polymorphic containers with value semantics in C++? The question was asked slightly incorrectly. It should have been more like: Can I have STL containers of a base type stored by-value in which the elements exhibit polymorphic behavior? If you are asking the question in terms of C++, the answer is "no." At some point, you will slice objects stored by-value. Now I ask the question again, but strictly in terms of C++11. With the changes to the language and the standard libraries, is it now possible to store polymorphic objects by value in an STL container? I'm well aware of the possibility of storing a smart pointer to the base class in the container -- this is not what I'm looking for, as I'm trying to construct objects on the stack without using new. Consider if you will (from the linked post) as basic C++ example: #include <iostream> using namespace std; class Parent { public: Parent() : parent_mem(1) {} virtual void write() { cout << "Parent: " << parent_mem << endl; } int parent_mem; }; class Child : public Parent { public: Child() : child_mem(2) { parent_mem = 2; } void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; } int child_mem; }; int main(int, char**) { // I can have a polymorphic container with pointer semantics vector<Parent*> pointerVec; pointerVec.push_back(new Parent()); pointerVec.push_back(new Child()); pointerVec[0]->write(); pointerVec[1]->write(); // Output: // // Parent: 1 // Child: 2, 2 // But I can't do it with value semantics vector<Parent> valueVec; valueVec.push_back(Parent()); valueVec.push_back(Child()); // gets turned into a Parent object :( valueVec[0].write(); valueVec[1].write(); // Output: // // Parent: 1 // Parent: 2 }

    Read the article

  • why is Active Record firing extra query when I use Includes method to fetch data

    - by riddhi_agrawal
    I have the following model structure: class Group < ActiveRecord::Base has_many :group_products, :dependent => :destroy has_many :products, :through => :group_products end class Product < ActiveRecord::Base has_many :group_products, :dependent => :destroy has_many :groups, :through => :group_products end class GroupProduct < ActiveRecord::Base belongs_to :group belongs_to :product end I wanted to minimize my database queries so I decided to use includes.In the console I tried something like, groups = Group.includes(:products) my development logs show the following calls, Group Load (403.0ms) SELECT `groups`.* FROM `groups` GroupProduct Load (60.0ms) SELECT `group_products`.* FROM `group_products` WHERE (`group_products`.group_id IN (1,3,14,15,16,18,19,20,21,22,23,24,25,26,27,28,29,30,33,42,49,51)) Product Load (22.0ms) SELECT `products`.* FROM `products` WHERE (`products`.`id` IN (382,304,353,12,63,103,104,105,262,377,263,264,265,283,284,285,286,287,302,306,307,308,328,335,336,337,340,355,59,60,61,247,309,311,66,30,274,294,324,350,140,176,177,178,64,240,327,332,338,380,383,252,254,255,256,257,325,326)) Product Load (10.0ms) SELECT `products`.* FROM `products` WHERE (`products`.`id` = 377) LIMIT 1 I could analyze the initial three calls were necessary but don't get the reason why the last database call is made, Product Load (10.0ms) SELECT `products`.* FROM `products` WHERE (`products`.`id` = 377) LIMIT 1 Any idea why this is happening? Thanks in advance. :)

    Read the article

  • Create Rails model with argument of associated model?

    - by Kyle Carlson
    I have two models, User and PushupReminder, and a method create_a_reminder in my PushupReminder controller (is that the best place to put it?) that I want to have create a new instance of a PushupReminder for a given user when I pass it a user ID. I have the association via the user_id column working correctly in my PushupReminder table and I've tested that I can both create reminders & send the reminder email correctly via the Rails console. Here is a snippet of the model code: class User < ActiveRecord::Base has_many :pushup_reminders end class PushupReminder < ActiveRecord::Base belongs_to :user end And the create_a_reminder method: def create_a_reminder(user) @user = User.find(user) @reminder = PushupReminder.create(:user_id => @user.id, :completed => false, :num_pushups => @user.pushups_per_reminder, :when_sent => Time.now) PushupReminderMailer.reminder_email(@user).deliver end I'm at a loss for how to run that create_a_reminder method in my code for a given user (eventually will be in a cron job for all my users). If someone could help me get my thinking on the right track, I'd really appreciate it. Thanks!

    Read the article

  • How to save the values of one model in another?

    - by ragupathi
    I have user model and Language model where the language model contains different languages and i want the user to select the languages from that model and it should be stored for the corresponding user. Consider there are five languages A, B, C, D, E then the user has to select from the languages. Suppose user 1 selects A and C whereas user 2 selects B and D then the languages has to be stored for that user. How can i do this? please help me.

    Read the article

  • Rails valiation among a three model relationship

    - by Andrew
    I'm working on a three model relationship with one aspect that I'm not sure how to approach. Here's the basic relationship: class Taxonomy has_many :terms # attribute: `inclusive`, default => false end class Term belongs_to :taxonomy has_and_belongs_to_many :photos end class Photo has_and_belongs_to_many :terms end This is pretty straightforward stuff except for one thing: A Taxonomy can be either 'Inclusive' or 'Exclusive'. Exclusive means the terms are mutually exclusive, Inclusive means they're not. So, if a Taxonomy is exclusive ie. taxonomy.inclusive = false, then there can only be one term from that taxonomy attached to a given photo. Now, I can handle this on the client-side without a problem, but I am not quite sure how to set up a validation on Photos (or somewhere else) that says basically: "validate that no more than one term from an exclusive taxonomy is associated with this record." Any ideas on how to do that?

    Read the article

  • Windows Vista, Default Programs API, file format associations, and (un)installers - explosive mix!

    - by Alex T.
    My application is a rather well behaved Windows citizen, so when I ported it to Windows Vista/7 I replaced my custom file format association code with support for the Default Programs API. However I ran into a problem when trying to make uninstaller for my application - there seems to be no way to remove file format associations via Default Programs API. I tried to call IApplicationAssociationRegistration::ClearUserAssociations but it actually removes all associations, including the ones for other applications - completely restoring default state of the OS (which is of course unacceptable). I tried to call IApplicationAssociationRegistration::SetAppAsDefault to return file format associations to the previous "owner" - but it does not help, because my application handles many unique file formats which the OS does not support and there is no previous "owners". And Windows does not allow to pass empty strings to SetAppAsDefault... So what do I do? Any good solutions?

    Read the article

  • Is there a way to have three way habtm associations in rails / activerecord?

    - by txwikinger
    Often three (or more) way associations are needed for habtm associations. For instance a permission model with roles. A particular area of functionality has many users which can access many areas. The permissions on the area are setup via roles (habtm) The user/roles association is also habtm The permissions (read, write, delete, etc) are habtm towards roles. How would that be best done with rails/activerecord?

    Read the article

  • How to perform a non-polymorphic HQL query in Hibernate?

    - by Eli Acherkan
    Hi all, I'm using Hibernate 3.1.1, and in particular, I'm using HQL queries. According to the documentation, Hibernate's queries are polymorphic: A query like: from Cat as cat returns instances not only of Cat, but also of subclasses like DomesticCat. How can I query for instances of Cat, but not of any of its subclasses? I'd like to be able to do it without having to explicitly mention each subclass. I'm aware of the following options, and don't find them satisfactory: Manually filtering the instances after the query, OR: Manually adding a WHERE clause on the discriminator column. It would make sense for Hibernate to allow the user to decide whether a query should be polymorphic or not, but I can't find such an option. Thanks in advance!

    Read the article

  • How to delete ProgIDs from other user accounts when uninstalling from Windows?

    - by Mordachai
    I've been investigating "how should a modern windows c++ application register its file types" with Windows (see http://stackoverflow.com/questions/2828637/c-how-do-i-correctly-register-and-unregister-file-type-associations-for-our-ap). And having combed through the various MSDN articles on the subject, the summary appears to be as follows: The installer (elevated) should register the global ProgID HKLM\Software\Classes\my-app.my-doc[.version] (e.g. HKLM\Software\Classes\TextPad.text) The installer also configures default associations for its document types (e.g. .myext) and points this to the aforementioned global ProgID in HKLM. NOTE: a user interface should be provided here to allow the user to either accept all default associations, or to customize which associations should be set. The application, running standard (unelevated), should provide a UI for allowing the current user to set their personal associations as is available in the installer, except that these associations are stored in HKCU\Software\Classes (per user, not per machine). The UN-installer is then responsible for deleting all registered ProgIDs (but should leave the actual file associations alone, as Windows is smart enough to handle associations pointing to missing ProgIDs, and this is the specified desired behavior by MSDN). So that schema sounds reasonable to me, except when I consider #4: How does an uninstaller, running elevated for a given user account, delete any per-user ProgIDs created in step #3 for other users? As I understand things, even in elevated mode, an uninstaller cannot go into another user's registry hive and delete items? Or can it? Does it have to load each given user hive first? What are the rules here? Thanks for any insight you might have to offer! EDIT: See below for the solution (My question was founded in confusion)

    Read the article

  • How to deserialize from json to ActiveRecord objects with associations?

    - by Carmine Paolino
    In my Rails application there is a model that has some has_one associations (this is a fabricated example): class Person::Admin < ActiveRecord::Base has_one :person_monthly_revenue has_one :dude_monthly_niceness accepts_nested_attributes_for :person_monthly_revenue, :dude_monthly_niceness end class Person::MonthlyRevenue < ActiveRecord::Base belongs_to :person_admin end class Dude::MonthlyNiceness < ActiveRecord::Base belongs_to :person_admin end The application talks to a backend that computes some data and returns a piece of JSON like this: { "dude_monthly_niceness": { "february": 1.1153232569518972, "october": 1.1250217200558268, "march": 1.3965786869658541, "august": 1.6293418014601631, "september": 1.4062771500697835, "may": 1.7166279693955291, "january": 1.0086401628086725, "june": 1.5711510228365859, "april": 1.5614525597326563, "december": 0.99894169970474289, "july": 1.7263264324994585, "november": 0.95044938418509506 }, "person_monthly_revenue": { "february": 10.585596551505297, "october": 10.574823016656749, "march": 9.9125274764852787, "august": 9.2111604702328922, "september": 9.7905249446675153, "may": 9.1329712474607962, "january": 10.479614016604238, "june": 9.3710235926961936, "april": 9.5897372624830304, "december": 10.052587677671438, "july": 8.9508877843925561, "november": 10.925339756096172 }, } To deserialize it, I use ActiveRecord's from_json, but instead of a Person::Admin object with all the associations in place, I get this error: >> Person::Admin.new.from_json(json) NameError: uninitialized constant Person::Admin::DudeMonthlyNiceness Am I doing something wrong? Is there a better way to deserialize data? (I can modify the backend easily)

    Read the article

  • How to find the most recent associations created between two objects with Rails?

    - by Kevin
    Hi, I have a user model, a movie model and this association in user.rb (I use has_many :through because there are other associations between these two models): has_many :has_seens has_many :movies_seen, :through = :has_seens, :source = :movie I'm trying to get an array of the ten most recent has_seens associations created. For now, the only solution I found is to crawl through all the users, creating an array with every user.has_seens found, then sort the array by has_seen.created_at and only keep the last 10 items… Seems like a heavy operation. Is there a better way? Kevin

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5 Part 1: Table per Hierarchy (TPH)

    - by mortezam
    A simple strategy for mapping classes to database tables might be “one table for every entity persistent class.” This approach sounds simple enough and, indeed, works well until we encounter inheritance. Inheritance is such a visible structural mismatch between the object-oriented and relational worlds because object-oriented systems model both “is a” and “has a” relationships. SQL-based models provide only "has a" relationships between entities; SQL database management systems don’t support type inheritance—and even when it’s available, it’s usually proprietary or incomplete. There are three different approaches to representing an inheritance hierarchy: Table per Hierarchy (TPH): Enable polymorphism by denormalizing the SQL schema, and utilize a type discriminator column that holds type information. Table per Type (TPT): Represent "is a" (inheritance) relationships as "has a" (foreign key) relationships. Table per Concrete class (TPC): Discard polymorphism and inheritance relationships completely from the SQL schema.I will explain each of these strategies in a series of posts and this one is dedicated to TPH. In this series we'll deeply dig into each of these strategies and will learn about "why" to choose them as well as "how" to implement them. Hopefully it will give you a better idea about which strategy to choose in a particular scenario. Inheritance Mapping with Entity Framework Code FirstAll of the inheritance mapping strategies that we discuss in this series will be implemented by EF Code First CTP5. The CTP5 build of the new EF Code First library has been released by ADO.NET team earlier this month. EF Code-First enables a pretty powerful code-centric development workflow for working with data. I’m a big fan of the EF Code First approach, and I’m pretty excited about a lot of productivity and power that it brings. When it comes to inheritance mapping, not only Code First fully supports all the strategies but also gives you ultimate flexibility to work with domain models that involves inheritance. The fluent API for inheritance mapping in CTP5 has been improved a lot and now it's more intuitive and concise in compare to CTP4. A Note For Those Who Follow Other Entity Framework ApproachesIf you are following EF's "Database First" or "Model First" approaches, I still recommend to read this series since although the implementation is Code First specific but the explanations around each of the strategies is perfectly applied to all approaches be it Code First or others. A Note For Those Who are New to Entity Framework and Code-FirstIf you choose to learn EF you've chosen well. If you choose to learn EF with Code First you've done even better. To get started, you can find a great walkthrough by Scott Guthrie here and another one by ADO.NET team here. In this post, I assume you already setup your machine to do Code First development and also that you are familiar with Code First fundamentals and basic concepts. You might also want to check out my other posts on EF Code First like Complex Types and Shared Primary Key Associations. A Top Down Development ScenarioThese posts take a top-down approach; it assumes that you’re starting with a domain model and trying to derive a new SQL schema. Therefore, we start with an existing domain model, implement it in C# and then let Code First create the database schema for us. However, the mapping strategies described are just as relevant if you’re working bottom up, starting with existing database tables. I’ll show some tricks along the way that help you dealing with nonperfect table layouts. Let’s start with the mapping of entity inheritance. -- The Domain ModelIn our domain model, we have a BillingDetail base class which is abstract (note the italic font on the UML class diagram below). We do allow various billing types and represent them as subclasses of BillingDetail class. As for now, we support CreditCard and BankAccount: Implement the Object Model with Code First As always, we start with the POCO classes. Note that in our DbContext, I only define one DbSet for the base class which is BillingDetail. Code First will find the other classes in the hierarchy based on Reachability Convention. public abstract class BillingDetail  {     public int BillingDetailId { get; set; }     public string Owner { get; set; }             public string Number { get; set; } } public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } public class CreditCard : BillingDetail {     public int CardType { get; set; }                     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } } public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; } } This object model is all that is needed to enable inheritance with Code First. If you put this in your application you would be able to immediately start working with the database and do CRUD operations. Before going into details about how EF Code First maps this object model to the database, we need to learn about one of the core concepts of inheritance mapping: polymorphic and non-polymorphic queries. Polymorphic Queries LINQ to Entities and EntitySQL, as object-oriented query languages, both support polymorphic queries—that is, queries for instances of a class and all instances of its subclasses, respectively. For example, consider the following query: IQueryable<BillingDetail> linqQuery = from b in context.BillingDetails select b; List<BillingDetail> billingDetails = linqQuery.ToList(); Or the same query in EntitySQL: string eSqlQuery = @"SELECT VAlUE b FROM BillingDetails AS b"; ObjectQuery<BillingDetail> objectQuery = ((IObjectContextAdapter)context).ObjectContext                                                                          .CreateQuery<BillingDetail>(eSqlQuery); List<BillingDetail> billingDetails = objectQuery.ToList(); linqQuery and eSqlQuery are both polymorphic and return a list of objects of the type BillingDetail, which is an abstract class but the actual concrete objects in the list are of the subtypes of BillingDetail: CreditCard and BankAccount. Non-polymorphic QueriesAll LINQ to Entities and EntitySQL queries are polymorphic which return not only instances of the specific entity class to which it refers, but all subclasses of that class as well. On the other hand, Non-polymorphic queries are queries whose polymorphism is restricted and only returns instances of a particular subclass. In LINQ to Entities, this can be specified by using OfType<T>() Method. For example, the following query returns only instances of BankAccount: IQueryable<BankAccount> query = from b in context.BillingDetails.OfType<BankAccount>() select b; EntitySQL has OFTYPE operator that does the same thing: string eSqlQuery = @"SELECT VAlUE b FROM OFTYPE(BillingDetails, Model.BankAccount) AS b"; In fact, the above query with OFTYPE operator is a short form of the following query expression that uses TREAT and IS OF operators: string eSqlQuery = @"SELECT VAlUE TREAT(b as Model.BankAccount)                       FROM BillingDetails AS b                       WHERE b IS OF(Model.BankAccount)"; (Note that in the above query, Model.BankAccount is the fully qualified name for BankAccount class. You need to change "Model" with your own namespace name.) Table per Class Hierarchy (TPH)An entire class hierarchy can be mapped to a single table. This table includes columns for all properties of all classes in the hierarchy. The concrete subclass represented by a particular row is identified by the value of a type discriminator column. You don’t have to do anything special in Code First to enable TPH. It's the default inheritance mapping strategy: This mapping strategy is a winner in terms of both performance and simplicity. It’s the best-performing way to represent polymorphism—both polymorphic and nonpolymorphic queries perform well—and it’s even easy to implement by hand. Ad-hoc reporting is possible without complex joins or unions. Schema evolution is straightforward. Discriminator Column As you can see in the DB schema above, Code First has to add a special column to distinguish between persistent classes: the discriminator. This isn’t a property of the persistent class in our object model; it’s used internally by EF Code First. By default, the column name is "Discriminator", and its type is string. The values defaults to the persistent class names —in this case, “BankAccount” or “CreditCard”. EF Code First automatically sets and retrieves the discriminator values. TPH Requires Properties in SubClasses to be Nullable in the Database TPH has one major problem: Columns for properties declared by subclasses will be nullable in the database. For example, Code First created an (INT, NULL) column to map CardType property in CreditCard class. However, in a typical mapping scenario, Code First always creates an (INT, NOT NULL) column in the database for an int property in persistent class. But in this case, since BankAccount instance won’t have a CardType property, the CardType field must be NULL for that row so Code First creates an (INT, NULL) instead. If your subclasses each define several non-nullable properties, the loss of NOT NULL constraints may be a serious problem from the point of view of data integrity. TPH Violates the Third Normal FormAnother important issue is normalization. We’ve created functional dependencies between nonkey columns, violating the third normal form. Basically, the value of Discriminator column determines the corresponding values of the columns that belong to the subclasses (e.g. BankName) but Discriminator is not part of the primary key for the table. As always, denormalization for performance can be misleading, because it sacrifices long-term stability, maintainability, and the integrity of data for immediate gains that may be also achieved by proper optimization of the SQL execution plans (in other words, ask your DBA). Generated SQL QueryLet's take a look at the SQL statements that EF Code First sends to the database when we write queries in LINQ to Entities or EntitySQL. For example, the polymorphic query for BillingDetails that you saw, generates the following SQL statement: SELECT  [Extent1].[Discriminator] AS [Discriminator],  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift],  [Extent1].[CardType] AS [CardType],  [Extent1].[ExpiryMonth] AS [ExpiryMonth],  [Extent1].[ExpiryYear] AS [ExpiryYear] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] IN ('BankAccount','CreditCard') Or the non-polymorphic query for the BankAccount subclass generates this SQL statement: SELECT  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] = 'BankAccount' Note how Code First adds a restriction on the discriminator column and also how it only selects those columns that belong to BankAccount entity. Change Discriminator Column Data Type and Values With Fluent API Sometimes, especially in legacy schemas, you need to override the conventions for the discriminator column so that Code First can work with the schema. The following fluent API code will change the discriminator column name to "BillingDetailType" and the values to "BA" and "CC" for BankAccount and CreditCard respectively: protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {     modelBuilder.Entity<BillingDetail>()                 .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue("BA"))                 .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue("CC")); } Also, changing the data type of discriminator column is interesting. In the above code, we passed strings to HasValue method but this method has been defined to accepts a type of object: public void HasValue(object value); Therefore, if for example we pass a value of type int to it then Code First not only use our desired values (i.e. 1 & 2) in the discriminator column but also changes the column type to be (INT, NOT NULL): modelBuilder.Entity<BillingDetail>()             .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue(1))             .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue(2)); SummaryIn this post we learned about Table per Hierarchy as the default mapping strategy in Code First. The disadvantages of the TPH strategy may be too serious for your design—after all, denormalized schemas can become a major burden in the long run. Your DBA may not like it at all. In the next post, we will learn about Table per Type (TPT) strategy that doesn’t expose you to this problem. References ADO.NET team blog Java Persistence with Hibernate book a { text-decoration: none; } a:visited { color: Blue; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } p.MsoNormal { margin-top: 0in; margin-right: 0in; margin-bottom: 10.0pt; margin-left: 0in; line-height: 115%; font-size: 11.0pt; font-family: "Calibri" , "sans-serif"; }

    Read the article

  • To Interface or Not?: Creating a polymorphic model relationship in Ruby on Rails dynamically..

    - by Globalkeith
    Please bear with me for a moment as I try to explain exactly what I would like to achieve. In my Ruby on Rails application I have a model called Page. It represents a web page. I would like to enable the user to arbitrarily attach components to the page. Some examples of "components" would be Picture, PictureCollection, Video, VideoCollection, Background, Audio, Form, Comments. Currently I have a direct relationship between Page and Picture like this: class Page < ActiveRecord::Base has_many :pictures, :as => :imageable, :dependent => :destroy end class Picture < ActiveRecord::Base belongs_to :imageable, :polymorphic => true end This relationship enables the user to associate an arbitrary number of Pictures to the page. Now if I want to provide multiple collections i would need an additional model: class PictureCollection < ActiveRecord::Base belongs_to :collectionable, :polymorphic => true has_many :pictures, :as => :imageable, :dependent => :destroy end And alter Page to reference the new model: class Page < ActiveRecord::Base has_many :picture_collections, :as => :collectionable, :dependent => :destroy end Now it would be possible for the user to add any number of image collections to the page. However this is still very static in term of the :picture_collections reference in the Page model. If I add another "component", for example :video_collections, I would need to declare another reference in page for that component type. So my question is this: Do I need to add a new reference for each component type, or is there some other way? In Actionscript/Java I would declare an interface Component and make all components implement that interface, then I could just have a single attribute :components which contains all of the dynamically associated model objects. This is Rails, and I'm sure there is a great way to achieve this, but its a tricky one to Google. Perhaps you good people have some wise suggestions. Thanks in advance for taking the time to read and answer this.

    Read the article

  • Broke NetBeans file associations in Windows XP how do I get them back?

    - by Serhiy
    I broke my file association in XP... Does anyone have any clue how to fix it? When I right click and select Open With... the application I want to use (NetBeans) to open the file is not on the list... and when I browse for it it won't let me select it (well it does but then won't add it to the list). The way I broke it is by installing 6.7 and then uninstalling 6.5.... since then my file associations have all been broken. I even tried uninstalling NetBeans and reinstalling it again... no luck... I even went as far as adding my own action called "OpenIt" to the file types I wanted... and that works... but only if the file/folders that contain in don't have any spaces... otherwise NetBeans throws a ".....does not exist, or is not a plain file". Thus nothing off the desktop can be opened... Does anyone know of how I can fix this problem? Thanks.

    Read the article

  • Broke NetBeans file associations in Windows XP how do I get them back?

    - by Serhiy
    Hello... I broke my file association in XP... Does anyone have any clue how to fix it? When I right click and select Open With... the application I want to use (NetBeans) to open the file is not on the list... and when I browse for it it won't let me select it (well it does but then won't add it to the list). The way I broke it is by installing 6.7 and then uninstalling 6.5.... since then my file associations have all been broken. I even tried uninstalling NetBeans and reinstalling it again... no luck... I even went as far as adding my own action called "OpenIt" to the file types I wanted... and that works... but only if the file/folders that contain in don't have any spaces... otherwise NetBeans throws a ".....does not exist, or is not a plain file". Thus nothing off the desktop can be opened... Does anyone know of how I can fix this problem? Thanks.

    Read the article

  • How do polymorphic inline caches work with mutable types?

    - by kingkilr
    A polymorphic inline cache works by caching the actual method by the type of the object, in order to avoid the expensive lookup procedures (usually a hashtable lookup). How does one handle the type comparison if the type objects are mutable (i.e. the method might be monkey patched into something different at run time). The one idea I've come up with would be a "class counter" that gets incremented each time a method is adjusted, however this seems like it would be exceptionally expensive in a heavily monkey patched environ since it would kill all the PICs for that class, even if the methods for them weren't altered. I'm sure there must be a good solution to this, as this issue is directly applicable to Javascript and AFAIK all 3 of the big JS VMs have PICs (wow acronym ahoy).

    Read the article

  • Model association changes in production environment, specifically converting a model to polymorphic?

    - by dustmoo
    Hi everyone, I was hoping I could get feedback on major changes to how a model works in an app that is in production already. In my case I have a model Record, that has_many PhoneNumbers. Currently it is a typical has_many belongs_to association with a record having many PhoneNumbers. Of course, I now have a feature of adding temporary, user generated records and these records will have PhoneNumbers too. I 'could' just add the user_record_id to the PhoneNumber model, but wouldn't it be better for this to be a polymorphic association? And if so, if you change how a model associates, how in the heck would I update the production database without breaking everything? .< Anyway, just looking for best practices in a situation like this. Thanks!

    Read the article

  • Should I use polymorphic association, just a has_one, or attribute in this case?

    - by Angela
    I have three Models: Contact_Email, Contact_Letter, and Contact_Call. These represent the unique pairing of a Contact with a template for each of the three. For all of these, I want to record at least a status and date for the status. For example, "declined" on 5/10/10 or "responded" on 5/10/10 or something like that. I may in the future want to extend that. I later do want to be able to see all the instances that have the same status, such as "responded" or "meeting requested." What is the best way to do this? To make the three Contacts statusable and create a polymorphic association on a model called Status. Or just each Object of Contact_Email has_one Status?

    Read the article

  • Duplication in parallel inheritance hierarchies

    - by flamingpenguin
    Using an OO language with static typing (like Java), what are good ways to represent the following model invariant without large amounts of duplication. I have two (actually multiple) flavours of the same structure. Each flavour requires its own (unique to that flavour data) on each of the objects within that structure as well as some shared data. But within each instance of the aggregation only objects of one (the same) flavour are allowed. FooContainer can contain FooSources and FooDestinations and associations between the "Foo" objects BarContainer can contain BarSources and BarDestinations and associations between the "Bar" objects interface Container() { List<? extends Source> sources(); List<? extends Destination> destinations(); List<? extends Associations> associations(); } interface FooContainer() extends Container { List<? extends FooSource> sources(); List<? extends FooDestination> destinations(); List<? extends FooAssociations> associations(); } interface BarContainer() extends Container { List<? extends BarSource> sources(); List<? extends BarDestination> destinations(); List<? extends BarAssociations> associations(); } interface Source { String getSourceDetail1(); } interface FooSource extends Source { String getSourceDetail2(); } interface BarSource extends Source { String getSourceDetail3(); } interface Destination { String getDestinationDetail1(); } interface FooDestination extends Destination { String getDestinationDetail2(); } interface BarDestination extends Destination { String getDestinationDetail3(); } interface Association { Source getSource(); Destination getDestination(); } interface FooAssociation extends Association { FooSource getSource(); FooDestination getDestination(); String getFooAssociationDetail(); } interface BarAssociation extends Association { BarSource getSource(); BarDestination getDestination(); String getBarAssociationDetail(); }

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >