Search Results

Search found 1739 results on 70 pages for 'castle activerecord'.

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

  • ASP.NET MVC Using Castle Windsor IoC

    - by Mad Halfling
    I have an app, modelled on the one from Apress Pro ASP.NET MVC that uses castle windsor's IoC to instantiate the controllers with their respective repositories, and this is working fine e.g. public class ItemController : Controller { private IItemsRepository itemsRepository; public ItemController(IItemsRepository windsorItemsRepository) { this.itemsRepository = windsorItemsRepository; } with using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Castle.Windsor; using Castle.Windsor.Configuration.Interpreters; using Castle.Core.Resource; using System.Reflection; using Castle.Core; namespace WebUI { public class WindsorControllerFactory : DefaultControllerFactory { WindsorContainer container; // The constructor: // 1. Sets up a new IoC container // 2. Registers all components specified in web.config // 3. Registers all controller types as components public WindsorControllerFactory() { // Instantiate a container, taking configuration from web.config container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle"))); // Also register all the controller types as transient var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes() where typeof(IController).IsAssignableFrom(t) select t; foreach (Type t in controllerTypes) container.AddComponentWithLifestyle(t.FullName, t, LifestyleType.Transient); } // Constructs the controller instance needed to service each request protected override IController GetControllerInstance(Type controllerType) { return (IController)container.Resolve(controllerType); } } } controlling the controller creation. I sometimes need to create other repository instances within controllers, to pick up data from other places, can I do this using the CW IoC, if so then how? I have been playing around with the creation of new controller classes, as they should auto-register with my existing code (if I can get this working, I can register them properly later) but when I try to instantiate them there is an obvious objection as I can't supply a repos class for the constructor (I was pretty sure that was the wrong way to go about it anyway). Any help (especially examples) would be much appreciated. Cheers MH

    Read the article

  • ActiveRecord table inheritence using set_table_names

    - by Jinyoung Kim
    Hi, I'm using ActiveRecord in Ruby on Rails. I have a table named documents(Document class) and I want to have another table data_documents(DataDocument) class which is effectively the same except for having different table name. In other words, I want two tables with the same behavior except for table name. class DataDocument < Document #set_table_name "data_documents" self.table_name = "data_documents" end My solution was to use class inheritance as above, yet this resulted in inconsistent SQL statement for create operation where there are both 'documents' table and 'data_documents' table. Can you figure out why and how I can make it work? >> DataDocument.create(:did=>"dd") ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'data_documents.did' in 'where clause': SELECT `documents`.id FROM `documents` WHERE (`data_documents`.`did` = BINARY 'dd') LIMIT 1 from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract_adapter.rb:212:in `log' from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/mysql_adapter.rb:320:in `execute' from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/mysql_adapter.rb:595:in `select' from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache' from /Users/lifidea/.gem/ruby/1.8/gems/activerecord-2.3.2/lib/active_record/connection_adapters/abstract/query_cache.rb:62:in `select_all'

    Read the article

  • Rails & ActiveRecord: Appending methods to models that inherit from ActiveRecord::Base

    - by PlankTon
    I have a standard ActiveRecord model with the following: class MyModel < ActiveRecord::Base custom_method :first_field, :second_field end At the moment, that custom_method is picked up by a module sent to ActiveRecord::Base. The functionality basically works, but of course, it attaches itself to every model class, not just MyModel. So if I have MyModel and MyOtherModel in the same action, it'll assume MyOtherModel has custom_method :first_field, :second_field as well. So, my question is: How do I attach a method (eg: def custom_method(*args)) to every class that inherits from ActiveRecord::Base, but not by attaching it to ActiveRecord::Base itself? Any ideas appreciated.

    Read the article

  • SQLServer Binary Data with ActiveRecord and JDBC

    - by John Duff
    I'm using the activerecord-jdbc-adapter with ActiveRecord to be able to access a SQLServer database for Rails Application running under jRuby and am having trouble inserting binary data. The Exception I am getting is below. Note I just have a blurb for the binary data from the fixtures that was working fine for MySQL. ActiveRecord::StatementInvalid: ActiveRecord::ActiveRecordError: Operand type clash: nvarchar is incompatible with image: INSERT INTO blobstorage_datachunks ([id], [datafile_id], [chunk_number], [data]) VALUES (369397133, 663419003, 0, N'GIF89a@') When I created the tables the migration had binary and SQLServer used Image instead. We're using Rails 2.3.5, SQLServer Express 2008. What I'm looking for is a way to get the binary data into SQLServer with ActiveRecord. Thanks in advance for the help.

    Read the article

  • nhibernate activerecord linq Contains problem

    - by Robert Ivanc
    Hi, I am having problems with the following query in Castle ActiveRecord 2.12: var q = from o in SodisceFMClientVAR.Queryable where taxnos2.Contains(o.TaxFileNo) select o; taxNos2 is an array of strings. When run I get an exception: + InnerException {"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"} System.Exception {System.ArgumentOutOfRangeException} StackTrace " at Castle.ActiveRecord.ActiveRecordBase.ExecuteQuery(IActiveRecordQuery query)\r\n at Castle.ActiveRecord.Linq.LinqResultWrapper`1.Populate()\r\n at Castle.ActiveRecord.Linq.LinqResultWrapper`1.GetEnumerator()\r\n at NHibernate.Linq.Query`1.GetEnumerator()\r\n at System.Linq.Buffer`1..ctor(IEnumerable`1 source)\r\n at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)\r\n at prosoft.skb.insolventnostDataAccess.InsolventnostDataAccAR.GetOurUsersListLS(ICollection`1 taxNos) in C:\\svn\\skb\\insolventnostWithAR\\prosoft.skb.insolventnostDataAccess\\InsolventnostDataAR.cs:line 214\r\n at prosoft.skb.insolventnostDataFromWS.InsolventnostFromWS.filterByOurUsers(IEnumerable`1 odprtiPostopki) in C:\\svn\\skb\\insolventnostWithAR\\prosoft.skb.insolventnostDataFromWS\\InsolventnostFromWS.cs:line 237\r\n at prosoft.skb.insolventnostDataFromWS.InsolventnostFromWS.SyncData() in C:\\svn\\skb\\insolventnostWithAR\\prosoft.skb.insolventnostDataFromWS\\InsolventnostFromWS.cs:line 53" string Does Contains even work in linq for nhibernate? I couldn't find anything via google... Is there a workaround? Thanks!

    Read the article

  • How do I merge a transient entity with a session using Castle ActiveRecordMediator?

    - by Daniel T.
    I have a Store and a Product entity: public class Store { public Guid Id { get; set; } public int Version { get; set; } public ISet<Product> Products { get; set; } } public class Product { public Guid Id { get; set; } public int Version { get; set; } public Store ParentStore { get; set; } public string Name { get; set; } } In other words, I have a Store that can contain multiple Products in a bidirectional one-to-many relationship. I'm sending data back and forth between a web browser and a web service. The following steps emulates the communication between the two, using session-per-request. I first save a new instance of a Store: using (new SessionScope()) { // this is data from the browser var store = new Store { Id = Guid.Empty }; ActiveRecordMediator.SaveAndFlush(store); } Then I grab the store out of the DB, add a new product to it, and then save it: using (new SessionScope()) { // this is data from the browser var product = new Product { Id = Guid.Empty, Name = "Apples" }); var store = ActiveRecordLinq.AsQueryable<Store>().First(); store.Products.Add(product); ActiveRecordMediator.SaveAndFlush(store); } Up to this point, everything works well. Now I want to update the Product I just saved: using (new SessionScope()) { // data from browser var product = new Product { Id = Guid.Empty, Version = 1, Name = "Grapes" }; var store = ActiveRecordLinq.AsQueryable<Store>().First(); store.Products.Add(product); // throws exception on this call ActiveRecordMediator.SaveAndFlush(store); } When I try to update the product, I get the following exception: a different object with the same identifier value was already associated with the session: 00000000-0000-0000-0000-000000000000, of entity:Product" As I understand it, the problem is that when I get the Store out of the database, it also gets the Product that's associated with it. Both entities are persistent. Then I tried to save a transient Product (the one that has the updated info from the browser) that has the same ID as the one that's already associated with the session, and an exception is thrown. However, I don't know how to get around this problem. If I could get access to a NHibernate.ISession, I could call ISession.Merge() on it, but it doesn't look like ActiveRecordMediator has anything similar (SaveCopy threw the same exception). Does anyone know the solution? Any help would be greatly appreciated!

    Read the article

  • Odd ActiveRecord model dynamic initialization bug in production

    - by qfinder
    I've got an ActiveRecord (2.3.5) model that occasionally exhibits incorrect behavior that appears to be related to a problem in its dynamic initialization. Here's the code: class Widget < ActiveRecord::Base extend ActiveSupport::Memoizable serialize :settings VALID_SETTINGS = %w(show_on_sale show_upcoming show_current show_past) VALID_SETTINGS.each do |setting| class_eval %{ def #{setting}=(val); self.settings[:#{setting}] = (val == "1"); end def #{setting}; self.settings[:#{setting}]; end } end def initialize_settings self.settings ||= { :show_on_sale => true, :show_upcoming => true } end after_initialize :initialize_settings # All the other stuff the model does end The idea was to use a single record field (settings) to persist a bunch of configuration data for this object, but allow all the settings to seamlessly work with form helpers and the like. (Why this approach makes sense here is a little out of scope, but let's assume that it does.) Net-net, Widget should end up with instance methods (eg #show_on_sale= #show_on_sale) for all the entires in the VALID_SETTINGS array. Any default values should be specified in initialize_settings. And indeed this works, mostly. In dev and staging, no problems at all. But in production, the app sometimes ends up in a state where a) any writes to the dynamically generated setters fail and b) none of the default values appear to be set - although my leading theory is that the dynamically generated reader methods are just broken. The code, db, and environment is otherwise identical between the three. A typical error message / backtrace on the fail looks like: IndexError: index 141145 out of string (eval):2:in []=' (eval):2:inshow_on_sale=' [GEM_ROOT]/gems/activerecord-2.3.5/lib/active_record/base.rb:2746:in send' [GEM_ROOT]/gems/activerecord-2.3.5/lib/active_record/base.rb:2746:inattributes=' [GEM_ROOT]/gems/activerecord-2.3.5/lib/active_record/base.rb:2742:in each' [GEM_ROOT]/gems/activerecord-2.3.5/lib/active_record/base.rb:2742:inattributes=' [GEM_ROOT]/gems/activerecord-2.3.5/lib/active_record/base.rb:2634:in `update_attributes!' ...(then controller and all the way down) Ideas or theories as to what might be going on? My leading theory is that something is going wrong in instance initialization wherein the class instance variable settings is ending up as a string rather than a hash. This explains both the above setter failure (:show_on_sale is being used to index into the string) and the fact that getters don't work (an out of bounds [] call on a string just returns nil). But then how and why might settings occasionally end up as a string rather than hash?

    Read the article

  • Ruby on Rails has_one Model Not Supplying ID Column

    - by Metric Scantlings
    I have a legacy rails (version 1.2.3) app which runs without issue on a number of servers (not to mention my local environment). Deployed to its newest server, though, and I now get ActiveRecord::StatementInvalid: Mysql::Error: #23000Column 'video_id' cannot be null errors. Below are the models/relationships, simplified: class Video < ActiveRecord::Base has_one(:user, :dependent => :destroy) end class User < ActiveRecord::Base belongs_to(:video) end And below is a rails console transcript of the relationships failing: >> video = Video.create(:title => 'New Video') => #<Video:0xb6d5e31c>... >> video.id => 5 >> video.user = User.create(:name => 'Tester') ActiveRecord::StatementInvalid: Mysql::Error: #23000Column 'video_id' cannot be null: INSERT INTO users (`name`, `video_id`) VALUES('Tester', NULL) from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/connection_adapters/abstract_adapter.rb:128:in `log' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/connection_adapters/mysql_adapter.rb:243:in `execute' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/connection_adapters/mysql_adapter.rb:253:in `insert' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1811:in `create_without_callbacks' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/callbacks.rb:254:in `create_without_timestamps' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/timestamp.rb:39:in `create' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1789:in `create_or_update_without_callbacks' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/callbacks.rb:242:in `create_or_update' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1545:in `save_without_validation' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/validations.rb:752:in `save_without_transactions' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:129:in `save' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/connection_adapters/abstract/database_statements.rb:59:in `transaction' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:95:in `transaction' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:121:in `transaction' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/transactions.rb:129:in `save' from /usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:451:in `create' from (irb):3 from :0 Has anyone else come across ActiveRecord not sending an ID when it clearly knows it?

    Read the article

  • MySQL Master/Slave with Castle Activerecord

    - by Kynth
    I have an existing web application using Castle Activerecord to interact with a single MySQL database. The Database has recently been reconfigured to replicate to a number of Slaves. How do you configure Castle Activerecord to direct writes to the MySQL Master and reads to the MySQL Slaves?

    Read the article

  • Castle Windsor using wrong component to satisfy a dependency

    - by Neil Barnwell
    I have the following component mapping in Windsor xml: <component id="dataSession.DbConnection" service="System.Data.IDbConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" type="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" lifestyle="custom" customLifestyleType="MyCompany.Castle.PerOperationLifestyle.PerOperationLifestyleManager, MyCompany.Castle"> <parameters> <connectionString>server=(local);database=MyCompany;trusted_connection=true;application name=OperationScopeTest;</connectionString> </parameters> </component> <component id="dataSession.DataContext" service="System.Data.Linq.DataContext, System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" type="MyCompany.BusinessLogic.MyCompanyDataContext, MyCompany.BusinessLogic" lifestyle="custom" customLifestyleType="MyCompany.Castle.PerOperationLifestyle.PerOperationLifestyleManager, MyCompany.Castle"> <parameters> <connection>${dataSession.DbConnection}</connection> </parameters> </component> However, when I ask the container for a DataContext, it actually uses the constructor requiring a connection string, despite the ${dataSession.DbConnection} being an IDbConnection. Why is this, and how to I make Windsor use the correct constructor?

    Read the article

  • Castle Windsor upgrade causes TypeLoadException for generic types

    - by Neil Barnwell
    I have the following mapping in my Castle Windsor xml file which has worked okay (unchanged) for some time: <component id="defaultBasicRepository" service="MyApp.Models.Repositories.IBasicRepository`1, MyApp.Models" type="MyApp.Models.Repositories.Linq.BasicRepository`1, MyApp.Models" lifestyle="perWebRequest"/> I got this from the Windsor documentation at http://www.castleproject.org/container/documentation/v1rc3/usersguide/genericssupport.html. Since I upgraded Windsor, I now get the following exception at runtime: Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.TypeLoadException: GenericArguments[0], 'T', on 'MyApp.Models.Repositories.Linq.BasicRepository`1[TEntity]' violates the constraint of type parameter 'TEntity'. Source Error: Line 44: public static void ConfigureIoC() Line 45: { Line 46: var windsor = new WindsorContainer("Windsor.xml"); Line 47: Line 48: ServiceLocator.SetLocatorProvider(() = new WindsorServiceLocator(windsor)); I'm using ASP.NET MVC 1.0, Visual Studio 2008 and Castle Windsor as downloaded from http://sourceforge.net/projects/castleproject/files/InversionOfControl/2.1/Castle-Windsor-2.1.1.zip/download Can anyone shed any light on this? I'm sure the upgrade of Castle Windsor is what caused it - it's been working well for ages.

    Read the article

  • castle PerRequestLifestyle not recognize

    - by Herman
    Hi all, New to Castle/Windsor, please bear with me. I am currently using the framework System.Web.Mvc.Extensibility and in its start up code, it registered HttpContextBase like the following: container.Register(Component.For<HttpContextBase>().LifeStyle.Transient.UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current))); What I wanted to do is to change the behavior and change the lifestyle of httpContextBase to be PerWebRequest. so I have change the code to the following: container.Register(Component.For<HttpContextBase>().LifeStyle.PerWebRequest.UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current))); However, when I do this, I got the following error: System.Configuration.ConfigurationErrorsException: Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule Add '<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.MicroKernel" />' to the <httpModules> section on your web.config which I did under <system.web> and <system.webServer>, however, I am still getting the same error. Any hints? Thanks in advance.

    Read the article

  • Castle Windsor, Fluent Nhibernate, and Automapping Isession closed problem

    - by SImon
    I'm new to the whole castle Windsor, Nhibernate, Fluent and Automapping stack so excuse my ignorance here. I didn't want to post another question on this as it seems there are already a huge number of questions that try to get a solution the Windsor nhib Isession management problem, but none of them have solved my problem so far. I am still getting a ISession is closed exception when I'm trying to call to the Db from my Repositories,Here is my container setup code. container.AddFacility<FactorySupportFacility>() .Register( Component.For<ISessionFactory>() .LifeStyle.Singleton .UsingFactoryMethod(() => Fluently.Configure() .Database( MsSqlConfiguration.MsSql2005. ConnectionString( c => c.Database("DbSchema").Server("Server").Username("UserName").Password("password"))) .Mappings ( m => m.AutoMappings.Add ( AutoMap.AssemblyOf<Message>(cfg) .Override<Client>(map => { map.HasManyToMany(x => x.SICCodes).Table("SICRefDataToClient"); }) .IgnoreBase<BaseEntity>() .Conventions.Add(DefaultCascade.SaveUpdate()) .Conventions.Add(new StringColumnLengthConvention(),new EnumConvention()) .Conventions.Add(new EnumConvention()) .Conventions.Add(DefaultLazy.Never()) ) ) .ExposeConfiguration(ConfigureValidator) .ExposeConfiguration(BuildDatabase) .BuildSessionFactory() as SessionFactoryImpl), Component.For<ISession>().LifeStyle.PerWebRequest.UsingFactoryMethod(kernel => kernel.Resolve<ISessionFactory>().OpenSession() )); In my repositories i inject private readonly ISession session; and use it as followes public User GetUser(int id) { User u; u = session.Get<User>(id); if (u != null && u.Id > 0) { NHibernateUtil.Initialize(u.UserDocuments); } return u; in my web.config inside <httpModules>. i have also added this line <add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor"/> I'm i still missing part of the puzzle here, i can't believe that this is such a complex thing to configure for a basic need of any web application development with nHibernate and castle Windsor. I have been trying to follow the code here windsor-nhibernate-isession-mvc and i posted my question there as they seemed to have the exact same issue but mine is not resolved.

    Read the article

  • Ruby types of collections in ActiveRecord

    - by kmorris511
    If I have an object with a collection of child objects in ActiveRecord, i.e. class Foo < ActiveRecord::Base has_many :bars, ... end and I attempt to run Array's find method against that collection: foo_instance.bars.find { ... } I receive: ActiveRecord::RecordNotFound: Couldn't find Bar without an ID I assume this is because ActiveRecord has hijacked the find method for its own purposes. Now, I can use detect and everything is fine. However to satisfy my own curiousity, I attempted to use metaprogramming to explicitly steal the find method back for one run: unbound_method = [].method('find').unbind unbound_method.bind(foo_instance.bars).call { ... } and I receive this error: TypeError: bind argument must be an instance of Array so clearly Ruby doesn't think foo_instance.bars is an Array and yet: foo_instance.bars.instance_of?(Array) -> true Can anybody help me with an explanation of this and of a way to get around it with metaprogramming?

    Read the article

  • Codeigniter: Combining activeRecord with manual queries?

    - by Industrial
    Hi everybody, I've though a bit about the activerecord vs. manual queries in Codeigniter. ActiveRecord is awesome when it's all about standard queries and holds development time really low. However, when there's a need to add some complexity to the queries, the ActiveRecord gets quite complicated to work with. Sub queries or complex joins gives atleast me a lot of headache. Since the current "$this-db-query" -call immediately executes the set query, it can't be combined with normal activeRecord calls. So, what can I do to combine the two methods? Thanks!

    Read the article

  • Ruby on Rails ActiveRecord/Include/Associations can't get my query to work

    - by Cypher
    I just started learning Rails and I'm just trying to set up query via associations. All the queries I try to write seem to be doing bizzare things and end up trying to query two tables parsed together with an '_' as one table. I have no clue why this would ever happen My tables are as follows: schools: id name variables: id name type var_entries: id variable_id entry school_entries: id school_id var_entry_id my rails association tables are $local = { :adapter => "mysql", :host => "localhost", :port => "3306".to_i, :database => "spy_2", :username =>"root", :password => "vertrigo" } class School < ActiveRecord::Base establish_connection $local has_many :school_entries has_many :var_entries, :through => school_entries end class Variable < ActiveRecord::Base establish_connection $local has_many :var_entries has_many :school_entries, :through => :var_entries end class VarEntry < ActiveRecord::Base establish_connection $local has_many_and_belongs_to :school_entries belongs_to :variables end class SchoolEntry < ActiveRecord::Base establish_connection $local belongs_to :school has_many :var_entries end I want to do this sql query: SELECT school_id, variable_id,rank FROM school_entries, variables, var_entries, schools WHERE var_entries.variable_id = variables.id AND school_entries.var_entry_id = var_entries.id AND schools.id = school_entries.school_id AND variables.type = 'number'; and put it into Rails notation: here is one of my many failed attempts schools = VarEntry.all(:include => [:school_entries, :variables], :conditions => "variables.type = 'number'") the error: 'const_missing': uninitialized constant VarEntry::Variables (NameError) if i remove variables schools = VarEntry.all(:include => [:school_entries, :variables], :conditions => "type = 'number'") the error is: Mysql::Error: Unkown column 'type' in 'where clause': SELECT * FROM 'var_entries' WHERE (type=number) (ActiveRecord::StatementInvalid) Can anyone tell me where I'm going horribly wrong?

    Read the article

  • trying to use ActiveRecord with Sinatra, Migration fails question

    - by David Lazar
    Hi, running Sinatra 1.0, I wanted to add a database table to my program. In my Rakefile I have a task task :environment do ActiveRecord::Base.establish_connection(YAML::load(File.open('config/database.yml'))["development"]) end I have a migration task in my namespace that calls the migration code: namespace :related_products do desc "run any migrations we may have in db/migrate" task :migrate => :environment do ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil ) end My console pukes out an error when the call to ActiveRecord::MIgrator.migrate() is made. rake aborted! undefined method `info' for nil:NilClass The migration code itself is pretty simple... and presents me with no clues as to what this missing info class is. class CreateStores < ActiveRecord::Migration def self.up create_table :stores do |t| t.string :name t.string :access_url t.timestamps end end def self.down drop_table :stores end end I am a little mystified here and am looking for some clues as to what might be wrong. Thanks!

    Read the article

  • many to many query for ActiveRecord

    - by JP
    I have three data models, Users, Conversations and Lines, where each conversation has many lines and certain participating users, each line has one conversation and one user and each user has many conversations and many lines. I have arranged these in ActiveRecord like this: class Line < ActiveRecord::Base belongs_to :conversation belongs_to :user end class User < ActiveRecord::Base has_and_belongs_to_many :conversations has_many :lines end class Conversation < ActiveRecord::Base has_many :lines has_and_belongs_to_many :users end If I want to create a new conversation with 4 users, where the users are either found or created inside the users table, how would I go about doing this? I thought I could do: c = Conversation.new c.users.find_or_create_by_username('myUsername') c.save But this will create a new username in the Users table even if that username already exists! (ie. running the above code 3 times will result in Users having 3 rows with 'myUsername' as the username, one for each conversation, rather than three conversations all with the same 'myUsername' entry listed in their associated users) I'm not sure how to search for this kind of information with google - can anyone help?

    Read the article

  • ActiveRecord/sqlite3 column type lost in table view?

    - by duncan
    I have the following ActiveRecord testcase that mimics my problem. I have a People table with one attribute being a date. I create a view over that table adding one column which is just that date plus 20 minutes: #!/usr/bin/env ruby %w|pp rubygems active_record irb active_support date|.each {|lib| require lib} ActiveRecord::Base.establish_connection( :adapter => "sqlite3", :database => "test.db" ) ActiveRecord::Schema.define do create_table :people, :force => true do |t| t.column :name, :string t.column :born_at, :datetime end execute "create view clowns as select p.name, p.born_at, datetime(p.born_at, '+' || '20' || ' minutes') as twenty_after_born_at from people p;" end class Person < ActiveRecord::Base validates_presence_of :name end class Clown < ActiveRecord::Base end Person.create(:name => "John", :born_at => DateTime.now) pp Person.all.first.born_at.class pp Clown.all.first.born_at.class pp Clown.all.first.twenty_after_born_at.class The problem is, the output is Time Time String When I expect the new datetime attribute of the view to be also a Time or DateTime in the ruby world. Any ideas? I also tried: create view clowns as select p.name, p.born_at, CAST(datetime(p.born_at, '+' || '20' || ' minutes') as datetime) as twenty_after_born_at from people p; With the same result.

    Read the article

  • Using Castle Windsor with FluentValidation In MVC

    - by user332022
    I'm working on getting FluentValidation working with Castle Windsor. I already have a wrapper around Castle Windsor. Here is the code for that: public class ResolveType { private static IWindsorContainer _windsorContainer; public static void Initialize( IWindsorContainer windsorContainer ) { _windsorContainer = windsorContainer; } public static T Of() { return _windsorContainer.Resolve(); } } I am trying to build the FluentValidation factory as is explained at http://www.jeremyskinner.co.uk/2010/02/22/using-fluentvalidation-with-an-ioc-container The article uses StructureMap, but I thought I could adapt it to Castle Windsor like this: public class CastleWindsorValidatorFactory : ValidatorFactoryBase { public override IValidator CreateInstance( Type validatorType) { return ResolveType.Of(); } } Notice, I'm just trying to call into my wrapper so that Windsor can resolve the type reference. The problem is that this doesn't compile. I get 'The type or namespace name 'validatorType' could not be found (are you missing a using directive or an assembly reference?)' How can I make this work?

    Read the article

  • castle monorails httpHandlers

    - by bogdanbrudiu
    I have a question and I hope you can help me solve it... I have a castle monorails application. In web.config file in httphandlers I have *.aspx maped to monorails (my hosting does not suport other extensions...) <add verb="*" path="*.aspx" type="Castle.MonoRail.Framework.MonoRailHttpHandlerFactory,Castle.MonoRail.Framework"/> The problem is that I have some Webforms pages that I want to work with aspx... So I am adding something like this to the web.config file... <add verb="*" path="connector.aspx*" type="System.Web.UI.PageHandlerFactory"/> <add verb="*" path="ChatPage.aspx*" type="System.Web.UI.PageHandlerFactory"/> <add verb="*" path="Logon.aspx*" type="System.Web.UI.PageHandlerFactory"/> Still it does not work.. What am I doing wrong?

    Read the article

  • Use component id in Castle Windsor generic object configuration

    - by ChoccyButton
    2 questions in one, but very much related. Is it possible with Castle Windsor to resolve a configuration entry such as - Assembly.Namespace.Object1`2[[${ComponentId1}],[${ComponentId2}]], Assembly Where ComponentId1 and ComponentId2 are defined as components. Castle Windsor doesn't seem to be resolving the ComponentId, it is just looking for ComponentId1 in the Castle.Windsor assembly. The second question comes in to play if you can't do the first question. If you have to use a full assembly reference instead of a ComponentId, how can you pass any parameters to the object being created? eg to set ComponentId1.Field1 = "blah", or pass something to the constructor of ComponentId1 Hope that makes sense Update - Following the request for code I've knocked together the following - Objects public class Wrapper<T, T1> where T : ICollector where T1:IProcessor { private T _collector; private T1 _processor; public Wrapper(T collector, T1 processor) { _collector = collector; _processor = processor; } public void GetData() { _collector.CollectData(); _processor.ProcessData(); } } public class Collector1 : ICollector { public void CollectData() { Console.WriteLine("Collecting data from Collector1 ..."); } } public class Processor1 : IProcessor { public void ProcessData() { Console.WriteLine("Processing data from Processor1 ..."); } } repeated so 3 of each type of object in the example Config <components> <component id="Collector1" service="CastleWindsorPlay.ICollector, CastleWindsorPlay" type="CastleWindsorPlay.Collector1, CastleWindsorPlay"/> <component id="Collector2" service="CastleWindsorPlay.ICollector, CastleWindsorPlay" type="CastleWindsorPlay.Collector2, CastleWindsorPlay"/> <component id="Collector3" service="CastleWindsorPlay.ICollector, CastleWindsorPlay" type="CastleWindsorPlay.Collector3, CastleWindsorPlay"/> <component id="Processor1" service="CastleWindsorPlay.IProcessor, CastleWindsorPlay" type="CastleWindsorPlay.Processor1, CastleWindsorPlay"/> <component id="Processor2" service="CastleWindsorPlay.IProcessor, CastleWindsorPlay" type="CastleWindsorPlay.Processor2, CastleWindsorPlay"/> <component id="Processor3" service="CastleWindsorPlay.IProcessor, CastleWindsorPlay" type="CastleWindsorPlay.Processor3, CastleWindsorPlay"/> <component id="Wrapper1" type="CastleWindsorPlay.Wrapper`2[[CastleWindsorPlay.Collector1, CastleWindsorPlay],[CastleWindsorPlay.Processor3, CastleWindsorPlay]], CastleWindsorPlay" /> </components> Instantiation var wrapper = (Wrapper<ICollector, IProcessor>) container.Resolve("Wrapper1"); wrapper.GetData(); This brief example errors with this error message though - Can't create component 'Wrapper1' as it has dependencies to be satisfied. Wrapper1 is waiting for the following dependencies: Services: - CastleWindsorPlay.Collector1 which was not registered. - CastleWindsorPlay.Processor3 which was not registered. The curious part about this is that I can get it to resolve Collector1 and Processor3 individually before the call to the wrapper, but the wrapper still can't see them. This is a basic example, the next thing I'd like to be able to do is when instantiating the Wrapper, set a property on the collector and/or processor. So it could be something like Collector.Id = 10, but set in the config where the wrapper is defined. Setting against the Collector component definition wouldn't work as I'd want to be able to instantiate multiple copies of each Collector, using different Id's Update 2 What I'm actually trying to do is have - <components> <component id="Wrapper1" type="CastleWindsorPlay.Wrapper`2[${Collector1}(id=1)],[${Processor3}]], CastleWindsorPlay" /> <component id="Wrapper2" type="CastleWindsorPlay.Wrapper`2[${Collector1}(id=3)],[${Processor3}]], CastleWindsorPlay" /> </components> Then have another object defined as <component id="Manager" type="CastleWindsorPlay.Manager,CastleWindsorPlay"> <parameters> <wrappers> <array> <item>${Wrapper1}</item> <item>${Wrapper2}</item> </array> </wrappers> </parameters> Then finally in code just be able to call - var manager = (Manager)container.Resolve("Manager"); This should return the manager object, with an array of wrappers populated and the wrappers configured with the correct Collector and Convertor. I know there are errors in the Castle config here, that's why I'm asking the question, I don't know how to set the config up to do what I'm after, or even if it's possible to do it in Castle Windsor

    Read the article

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