Search Results

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

Page 6/28 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Safe and polymorphic toEnum

    - by jetxee
    I'd like to write a safe version of toEnum: safeToEnum :: (Enum t, Bounded t) => Int -> Maybe t A naive implementation: safeToEnum :: (Enum t, Bounded t) => Int -> Maybe t safeToEnum i = if (i >= fromEnum (minBound :: t)) && (i <= fromEnum (maxBound :: t)) then Just . toEnum $ i else Nothing main = do print $ (safeToEnum 1 :: Maybe Bool) print $ (safeToEnum 2 :: Maybe Bool) And it doesn't work: safeToEnum.hs:3:21: Could not deduce (Bounded t1) from the context () arising from a use of `minBound' at safeToEnum.hs:3:21-28 Possible fix: add (Bounded t1) to the context of an expression type signature In the first argument of `fromEnum', namely `(minBound :: t)' In the second argument of `(>=)', namely `fromEnum (minBound :: t)' In the first argument of `(&&)', namely `(i >= fromEnum (minBound :: t))' safeToEnum.hs:3:56: Could not deduce (Bounded t1) from the context () arising from a use of `maxBound' at safeToEnum.hs:3:56-63 Possible fix: add (Bounded t1) to the context of an expression type signature In the first argument of `fromEnum', namely `(maxBound :: t)' In the second argument of `(<=)', namely `fromEnum (maxBound :: t)' In the second argument of `(&&)', namely `(i <= fromEnum (maxBound :: t))' As well as I understand the message, the compiler does not recognize that minBound and maxBound should produce exactly the same type as in the result type of safeToEnum inspite of the explicit type declaration (:: t). Any idea how to fix it?

    Read the article

  • Copying a Polymorphic object in C++

    - by doron
    I have base-class Base from which is derived Derived1, Derived2 and Derived3. I have constructed an instance for one of the the derived classes which I store as Base* a. I now need to make a deep copy of the object which I will store as Base* b. As far as I know, the normal way of copying a class is to use copy constructors and to overload operator=. However since I don't know whether a is of type Derived1, Derived2 or Derived3, I cannot think of a way of using either the copy constructor or operator=. The only way I can think of to cleanly make this work is to implement something like: class Base { public: virtual Base* Clone() = 0; }; and the implement Clone in in the derived class as in: class Derivedn : public Base { public: Base* Clone() { Derived1* ret = new Derived1; copy all the data members } }; Java tends to use Clone quite a bit is there more of a C++ way of doing this?

    Read the article

  • Polymorphic classes in templates

    - by soxarered
    Let's say we have a class hierarchy where we have a generic Animal class, which has several classes directly inherit from it (such as Dog, Cat, Horse, etc..). When using templates on this inheritance hierarchy, is it legal to just use SomeTemplateClass<Animal> and then shove in Dogs and Cats and Horses into this templated object? For example, assume we have a templated Stack class, where we want to host all sorts of animals. Can I simply state Stack<Animal> s; Dog d; s.push(d); Cat c; s.push(c);

    Read the article

  • JPA polymorphic oneToMany

    - by bob
    I couldn't figure out how to cleanly do a tag cloud with JPA where each db entity can have many tags. E.g Post can have 0 or more Tags User can have 0 or more Tags Is there a better way in JPA than having to make all the entities subclass something like Taggable abstract class? Where a a Tag entity would reference many Taggables. thank you

    Read the article

  • Managing memory of polymorphic timed events with DLL

    - by Milo
    Here is my issue. My Gui library that I made supports timed events. Basically, I have a class called TimedEvent which users inherit from. They then do: addTimedEvent(new DerivedTimedEvent(...)); However given the nature of timed events, I manage the memory afterwards. So when the timed event has done its thing, my library calls delete on it. Although it runs fine, that is because the exe and the library were both built with msvc 2008. I think I might have trouble if I have 2 versions of the runtime, one for the lib, and one for the exe. What can I do to fix this? I can't create a factory because the derived type is on the exe side of things. I also cannot ask the user to call delete since they might not have a way to keep track of time, or know if the event was delayed for whatever reason. Thanks

    Read the article

  • Polymorphic behavior not being implemented

    - by Garrett A. Hughes
    The last two lines of this code illustrate the problem: the compiler works when I use the reference to the object, but not when I assign the reference to an array element. The rest of the code is in the same package in separate files. BioStudent and ChemStudent are separate classes, as well as Student. package pkgPoly; public class Poly { public static void main(String[] arg) { Student[] stud = new Student[3]; // create a biology student BioStudent s1 = new BioStudent("Tom"); // create a chemistry student ChemStudent s2 = new ChemStudent("Dick"); // fill the student body with studs stud[0] = s0; stud[1] = s1; // compiler complains that it can't find symbol getMajor on next line System.out.println("major: " + stud[0].getMajor() ); // doesn't compile; System.out.println("major: " + s0.getMajor() ); // works: compiles and runs correctly } }

    Read the article

  • Why aren't Java's generics implicitly polymorphic?

    - by froadie
    I'm a bit confused about how Java generics handle inheritance / polymorphism. Assume the following hierarchy - Animal (Parent) Dog - Cat (Children) So suppose I have a method doSomething(List<Animal> animals). By all the rules of inheritance and polymorphism, I would assume that a List<Dog> is a List<Animal> and a List<Cat> is a List<Animal> - and so either one could be passed to this method. Not so. If I want to achieve this behavior, I have to explicitly tell the method to accept a list of any subset of Animal by saying doSomething(List<? extends Animal> animals). I understand that this is Java's behavior. My question is why? Why is polymorphism generally implicit, but when it comes to generics it must be specified?

    Read the article

  • C++: Could Polymorphic Copy Constructors work?

    - by 0xC0DEFACE
    Consider: class A { public: A( int val ) : m_ValA( val ) {} A( const A& rhs ) {} int m_ValA; }; class B : public A { public: B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {} B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {} int m_ValB; }; int main() { A* b1 = new B( 1, 2 ); A* b2 = new A( *b1 ); // ERROR...but what if it could work? return 0; } Would C++ be broken if "new A( b1 )" was able to resolve to creating a new B copy and returning an A? Would this even be useful?

    Read the article

  • How to model has_many with polymorphism?

    - by Daniel Abrahamsson
    I've run into a situation that I am not quite sure how to model. Suppose I have a User class, and a user has many services. However, these services are quite different, for example a MailService and a BackupService, so single table inheritance won't do. Instead, I am thinking of using polymorphic associations together with an abstract base class: class User < ActiveRecord::Base has_many :services end class Service < ActiveRecord::Base validates_presence_of :user_id, :implementation_id, :implementation_type belongs_to :user belongs_to :implementation, :polymorphic = true delegate :common_service_method, :name, :to => :implementation end #Base class for service implementations class ServiceImplementation < ActiveRecord::Base validates_presence_of :user_id, :on => :create has_one :service, :as => :implementation has_one :user, :through => :service after_create :create_service_record #Tell Rails this class does not use a table. def self.abstract_class? true end #Default name implementation. def name self.class.name end protected #Sets up a service object def create_service_record service = Service.new(:user_id => user_id) service.implementation = self service.save! end end class MailService < ServiceImplementation #validations, etc... def common_service_method puts "MailService implementation of common service method" end end #Example usage MailService.create(..., :user_id => user.id) BackupService.create(...., :user_id => user.id) user.services.each do |s| puts "#{user.name} is using #{s.name}" end #Daniel is using MailService, Daniel is using BackupService So, is this the best solution? Or even a good one? How have you solved this kind of problem?

    Read the article

  • nil object in view when building objects on two different associations

    - by Shako
    Hello all. I'm relatively new to Ruby on Rails so please don't mind my newbie level! I have following models: class Paintingdescription < ActiveRecord::Base belongs_to :paintings belongs_to :languages end class Paintingtitle < ActiveRecord::Base belongs_to :paintings belongs_to :languages end class Painting < ActiveRecord::Base has_many :paintingtitles, :dependent => :destroy has_many :paintingdescriptions, :dependent => :destroy has_many :languages, :through => :paintingdescriptions has_many :languages, :through => :paintingtitles end class Language < ActiveRecord::Base has_many :paintingtitles, :dependent => :nullify has_many :paintingdescriptions, :dependent => :nullify has_many :paintings, :through => :paintingtitles has_many :paintings, :through => :paintingdescriptions end In my painting new/edit view, I would like to show the painting details, together with its title and description in each of the languages, so I can store the translation of those field. In order to build the languagetitle and languagedescription records for my painting and each of the languages, I wrote following code in the new method of my Paintings_controller.rb: @temp_languages = @languages @languages.size.times{@painting.paintingtitles.build} @painting.paintingtitles.each do |paintingtitle| paintingtitle.language_id = @temp_languages[0].id @temp_languages.slice!(0) end @temp_languages = @languages @languages.size.times{@painting.paintingdescriptions.build} @painting.paintingdescriptions.each do |paintingdescription| paintingdescription.language_id = @temp_languages[0].id @temp_languages.slice!(0) end In form partial which I call in the new/edit view, I have <% form_for @painting, :html => { :multipart => true} do |f| %> ... <% languages.each do |language| %> <p> <%= label language, language.name %> <% paintingtitle = @painting.paintingtitles[counter] %> <% new_or_existing = paintingtitle.new_record? ? 'new' : 'new' %> <% prefix = "painting[#{new_or_existing}_title_attributes][]" %> <% fields_for prefix, paintingtitle do |paintingtitle_form| %> <%= paintingtitle_form.hidden_field :language_id%> <%= f.label :title %><br /> <%= paintingtitle_form.text_field :title%> <% end %> <% paintingdescription = @painting.paintingdescriptions[counter] %> <% new_or_existing = paintingdescription.new_record? ? 'new' : 'new' %> <% prefix = "painting[#{new_or_existing}_title_attributes][]" %> <% fields_for prefix, paintingdescription do |paintingdescription_form| %> <%= paintingdescription_form.hidden_field :language_id%> <%= f.label :description %><br /> <%= paintingdescription_form.text_field :description %> <% end %> </p> <% counter += 1 %> <% end %> ... <% end %> But, when running the code, ruby encounters a nil object when evaluating paintingdescription.new_record?: You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.new_record? However, if I change the order in which I a) build the paintingtitles and painting descriptions in the paintings_controller new method and b) show the paintingtitles and painting descriptions in the form partial then I get the nil on the paintingtitles.new_record? call. I always get the nil for the objects I build in second place. The ones I build first aren't nil in my view. Is it possible that I cannot build objects for 2 different associations at the same time? Or am I missing something else? Thanks in advance!

    Read the article

  • Active Record two belongs_to calls or single table inheritance

    - by ethyreal
    In linking a sports event to two teams, at first this seemed to make sense: events - id:integer - integer:home_team_id - integer:away_team_id teams - integer:id - string:name However I am troubled by how I would link that up in the active record model: class Event belongs_to :home_team, :class_name => 'Team', :foreign_key => "home_team_id" belongs_to :away_team, :class_name => 'Team', :foreign_key => "away_team_id" end Is that the best solution? In an answer to a similar question I was pointed to single table inheritance, and then later found polymorphic associations. Neither of which seemed to fit this association. Perhaps I am looking at this wrong, but I see no need to subclass a team into home and away teams since the distinction is only in where the game is played. If I did go with single table inheritance I wouldn't want each team to belong_to an event so would this work? # app/models/event.rb class Event < ActiveRecord::Base belongs_to :home_team belongs_to :away_team end # app/models/team.rb class Team < ActiveRecord::Base has_many :teams end # app/models/home_team.rb class HomeTeam < Team end # app/models/away_team.rb class AwayTeam < Team end I thought also about a has_many through association but that seems two much as I will only ever need two teams, but those two teams don't belong to any one event. event_teams - integer:event_id - integer:team_id - boolean:is_home Is there a cleaner more semantic way for making these associations in active record? or is one of these solutions the best choice? Thanks

    Read the article

  • How to add a has_many association on all models

    - by joshsz
    Right now I have an initializer that does this: ActiveRecord::Base.send :has_many, :notes, :as => :notable ActiveRecord::Base.send :accepts_nested_attributes_for, :notes It builds the association just fine, except when I load a view that uses it, the second load gives me: can't dup NilClass from: /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2184:in `dup' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2184:in `scoped_methods' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2188:in `current_scoped_methods' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2171:in `scoped?' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2439:in `send' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2439:in `initialize' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `new' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `build_association' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:423:in `build_record' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:102:in `build' (my app)/controllers/manifests_controller.rb:21:in `show' Any ideas? Am I doing this the wrong way? Interestingly if I move the association onto just the model I'm working with at the moment, I don't get this error. I figure I must be building the global association incorrectly.

    Read the article

  • How to build MVC Views that work with polymorphic domain model design?

    - by Johann de Swardt
    This is more of a "how would you do it" type of question. The application I'm working on is an ASP.NET MVC4 app using Razor syntax. I've got a nice domain model which has a few polymorphic classes, awesome to work with in the code, but I have a few questions regarding the MVC front-end. Views are easy to build for normal classes, but when it comes to the polymorphic ones I'm stuck on deciding how to implement them. The one (ugly) option is to build a page which handles the base type (eg. IContract) and has a bunch of if statements to check if we passed in a IServiceContract or ISupplyContract instance. Not pretty and very nasty to maintain. The other option is to build a view for each of these IContract child classes, breaking DRY principles completely. Don't like doing this for obvious reasons. Another option (also not great) is to split the view into chunks with partials and build partial views for each of the child types that are loaded into the main view for the base type, then deciding to show or hide the partial in a single if statement in the partial. Also messy. I've also been thinking about building a master page with sections for the fields that only occur in subclasses and to build views for each subclass referencing the master page. This looks like the least problematic solution? It will allow for fairly simple maintenance and it doesn't involve code duplication. What are your thoughts? Am I missing something obvious that will make our lives easier? Suggestions?

    Read the article

  • defining class relationships in c# and visual studio 2010

    - by andy
    Hey guys, in Visual Studio 2010 I can point to a bunch of classes and create a diagram. However, the diagram by default doesn't recognize any relationships between the classes, except inheritance and implementations. Is there a way, ideally by using Attributes, to define class and property relationships and associations in such a way that it is picked up by a new Class Diagram automatically? cheers!

    Read the article

  • Displaying pic for user through a question's answer

    - by bgadoci
    Ok, I am trying to display the profile pic of a user. The application I have set up allows users to create questions and answers (I am calling answers 'sites' in the code) the view in which I am trying to do so is in the /views/questions/show.html.erb file. It might also be of note that I am using the Paperclip gem. Here is the set up: Associations Users class User < ActiveRecord::Base has_many :questions, :dependent => :destroy has_many :sites, :dependent => :destroy has_many :notes, :dependent => :destroy has_many :likes, :through => :sites , :dependent => :destroy has_many :pics, :dependent => :destroy has_many :likes, :dependent => :destroy end Questions class Question < ActiveRecord::Base has_many :sites, :dependent => :destroy has_many :notes, :dependent => :destroy has_many :likes, :dependent => :destroy belongs_to :user end Answers (sites) class Site < ActiveRecord::Base belongs_to :question belongs_to :user has_many :notes, :dependent => :destroy has_many :likes, :dependent => :destroy has_attached_file :photo, :styles => { :small => "250x250>" } end Pics class Pic < ActiveRecord::Base has_attached_file :profile_pic, :styles => { :small => "100x100" } belongs_to :user end The /views/questions/show.html.erb is rendering the partial /views/sites/_site.html.erb which is calling the Answer (site) with: <% div_for site do %> <%=h site.description %> <% end %> I have been trying to do things like: <%=image_tag site.user.pic.profile_pic.url(:small) %> <%=image_tag site.user.profile_pic.url(:small) %> etc. But that is obviously wrong. My error directs me to the Questions#show action so I am imagining that I need to define something in there but not sure what. Is is possible to call the pic given the current associations, placement of the call, and if so what Controller additions do I need to make, and what line of code will call the pic? UPDATE: Here is the QuestionsController#show code: def show @question = Question.find(params[:id]) @sites = @question.sites.all(:select => "sites.*, SUM(likes.like) as like_total", :joins => "LEFT JOIN likes AS likes ON likes.site_id = sites.id", :group => "sites.id", :order => "like_total DESC") respond_to do |format| format.html # show.html.erb format.xml { render :xml => @question } end end

    Read the article

  • Rails Association Question...

    - by keruilin
    I have three models: User, RaceWeek, Race # Current associations: User has_many race_weeks; RaceWeek belongs to user; RaceWeek has many races; Race belongs to RaceWeek # So the user_id is a foreign key in RaceWeek and race_week_id is a foreign key in Race. # fastest_time is an attribute of the Race model. # QUESTION: What's the optimal way to retrieve a list of users who have the top X fastest race times?

    Read the article

  • Rails Associations - Callback Sequence/Magic

    - by satynos
    Taking following association declaration as an example: class Post has_many :comments end Just by declaring the has_many :comments, ActiveRecord adds several methods of which I am particularly interested in comments which returns array of comments. I browsed through the code and following seems to be the callback sequence: def has_many(association_id, options = {}, &extension) reflection = create_has_many_reflection(association_id, options, &extension) configure_dependency_for_has_many(reflection) add_association_callbacks(reflection.name, reflection.options) if options[:through] collection_accessor_methods(reflection, HasManyThroughAssociation) else collection_accessor_methods(reflection, HasManyAssociation) end end def collection_accessor_methods(reflection, association_proxy_class, writer = true) collection_reader_method(reflection, association_proxy_class) if writer define_method("#{reflection.name}=") do |new_value| # Loads proxy class instance (defined in collection_reader_method) if not already loaded association = send(reflection.name) association.replace(new_value) association end define_method("#{reflection.name.to_s.singularize}_ids=") do |new_value| ids = (new_value || []).reject { |nid| nid.blank? } send("#{reflection.name}=", reflection.class_name.constantize.find(ids)) end end end def collection_reader_method(reflection, association_proxy_class) define_method(reflection.name) do |*params| force_reload = params.first unless params.empty? association = association_instance_get(reflection.name) unless association association = association_proxy_class.new(self, reflection) association_instance_set(reflection.name, association) end association.reload if force_reload association end define_method("#{reflection.name.to_s.singularize}_ids") do if send(reflection.name).loaded? || reflection.options[:finder_sql] send(reflection.name).map(&:id) else send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map(&:id) end end end In this sequence of callbacks, where exactly is the actual SQL being executed for retrieving the comments when I do @post.comments ?

    Read the article

  • "Bootstrap" python script in the Windows shell without .py / .pyw associations

    - by PabloG
    Sometimes (in customer's PCs) I need a python script to execute in the Windows shell like a .CMD or .BAT, but without having the .py or .pyw extensions associated with PYTHON / PYTHONW. I came out with a pair of 'quick'n dirty' solutions: 1) """ e:\devtool\python\python.exe %0 :: or %PYTHONPATH%\python.exe goto eof: """ # Python test print "[works, but shows shell errors]" 2) @echo off for /f "skip=4 delims=xxx" %%l in (%0) do @echo %%l | e:\devtools\python\python.exe goto :eof ::---------- # Python test print "[works better, but is somewhat messy]" Do you know a better solution? (ie: more concise or elegant)

    Read the article

  • File association and msconfig broken. Malware?

    - by Moshe
    A friend of mine had an Acer laptop. It has Vista Home Basic. I can't get system properties open. Msconfig does not run. Also, exe filetype is asking me what program to run it with. How can I fix that? I'm running AVG now. Assuming nothing shows up, what are fixes to the above mentioned issues?

    Read the article

  • I tried changing my folder icon in windows XP and now whenever I click a folder it opens in a new wi

    - by widgisoft
    On some random afternoon I figured I could do better than the boring yellow icon; After a vain attempt at trying to change it to no avail I realised that now whenever I open a folder it opens in a "search" window. This happened because when I go to the "(file folder)" type, the only option in there is "find" that is not supposed to be the default; upon saving this form XP tries to do me a favour and sets this as the new default. Now whenever I try to click a folder it opens the search window. great.

    Read the article

  • Grails: Problem with nested associations in criteria builder

    - by Mr.B
    I have a frustrating problem with the criteria builder. I have an application in which one user has one calendar, and a calendar has many entries. Seems straightforward enough, but when I try to get the calendar entries for a given user, I can't access the user property (MissingMethodException). Here's the code: def getEntries(User user) { def entries = Entries.createCriteria().list() { calendar { user { eq("user.id", user.id) } } } } I have even tried the following variation: def getEntries(User user) { def entries = Entries.createCriteria().list() { calendar { eq("user", user) } } } That did not raise an exception, but didn't work either. Here's the relevant parts of the domain classes: class Calendar { static belongsTo = [user: User] static hasMany = [entries: Entries] ... } class User { Calendar calendar ... } class Entry { static belongsTo = [calendar: Calendar] ... } When Googling I came across a similar problem noted in early 2008: http://jira.codehaus.org/browse/GRAILS-1412 But according to that link this issue should have been solved long ago. What am I doing wrong?

    Read the article

  • Ubuntu: Getting rid of a mimetype entry

    - by Epaga
    I have a pesky mimetype entry that I can't seem to get rid of. Here is the current situation: xdg-mime query filetype myfile.mfe application/pesky Using assogiate I have found out the information about this mime type entry (but can't delete it there). I have the following 'pesky.xml' XML file which was used to create the mime type (as far as I can tell, since it exactly matches the entry in assogiate...): <?xml version='1.0'?> <mime-info xmlns='http://www.freedesktop.org/standard'> <mime-type type="application/pesky"> <comment>my pesky type</comment> <glob pattern="*.mfe"/> <magic priority="100"> <match type="string" offset="0" value="application/pesky"/> </magic> </mime-type> <mime-info> However, the following has no effect: sudo xdg-mime uninstall --mode system --novendor pesky.xml The file association remains. Any ideas?

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >