Search Results

Search found 13135 results on 526 pages for 'actor model'.

Page 147/526 | < Previous Page | 143 144 145 146 147 148 149 150 151 152 153 154  | Next Page >

  • Bulletin board - Database optimisation

    - by andrew
    This question is a follow on from this Question The project and problem The project I am currently working on is a bulletin board for a large non-profit organisation. The bulletin board will be used to allow inter-office communication within the organisation. I am building the application and have been having trouble extracting the results that I need from my database because I don't think it is properly normalized and because of limitations in my knowledge of relational database theory and mysql. I would appreciate input into the design of the board in general and in particular, ways that the database structure can be improved to facilitate efficient queries and help me develop this application and future application faster Business Logic The bulletin board will be used in the following way Posting bulletins and responses to bulletins Employees or 'users' in offices around the country will be able to post messages to the bulletin board.Bulletins must be posted to a location and categorised- i'll call these "bulletins". Users will be able to post any number of replies to any one bulletin and users will be able to reply to their own bulletin - i'll call these 'replies'. Rating bulletins and replies Users will be able to either 'like' or 'dislike' a bulletin or a reply and the total number of likes or dislikes will be shown for each bulletin or reply. Viewing the bulletin board and responses Bulletins can be displayed chronologically. Users can sort bulletins chronologically or chronologically by the latest reply to that bulletin(let me know if you need more explanation) When a particular bulletin is selected, replies to that bulletin will be displayed chronologically @PerformanceDBA - edited 10:34 est 28/12/10I have begun implementing the data model. I assume that the 6th data model is the physical model because it contains the associative tables. I am going to post any questions that I have below. I will put up a database dump once I am done. I will then put up a list of all the queries that I need to run on the database and begin writing them. I hope you had a good Christmas. I'm in Canada and there's snow! Implementation of Physical model

    Read the article

  • django simple approach to multi-field search

    - by Scott Willman
    I have a simple address book app that I want to make searchable. The model would look something like: class Address(models.Model): address1 = models.CharField("Address Line 1", max_length=128) address2 = models.CharField("Address Line 2", max_length=128) city = models.CharField("City", max_length=128) state = models.CharField("State", max_length=24) zipCode = models.CharField("Zip Code", max_length=24) def __unicode__(self): return "%s %s, %s, %s, %s" % (self.address1, self.address2, self.city, self.state, self.zipCode) class Entry(models.Model): name = models.CharField("Official School Name", max_length=128) createdBy = models.ForeignKey(User) address = models.ForeignKey(Address, unique=True) def __unicode__(self): return "%s - %s, %s" % (self.name, self.address.city, self.address.state) I want the searching to be fairly loose, like: Bank of America Los Angeles 91345. It seems like I want a field that contains all of those elements into one that I can search, but that also seems redundant. I was hoping I could add a method to the Entry model like this: def _getSearchText(self): return "%s %s %s" % (self.name, self.address, self.mascot) searchText = property(_getSearchText) ...and search that as a field, but I suppose that's wishful thinking... How should I approach this using basic Django and SqLite (this is a learning exercise). Thank you!!

    Read the article

  • Yii CGridView and dropdown filter

    - by Dmitriy Gunchenko
    I created dropdown filter, it's display, but don't worked right. As I anderstand trouble in search() method view: $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$model->search(), 'filter' => $model, 'columns'=>array( array( 'name' => 'client_id', 'filter' => CHtml::listData(Client::model()->findAll(), 'client_id', 'name'), 'value'=>'$data->client->name' ), 'task' ) )); I have to tables, and they relations are shown down model: public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'client' => array(self::BELONGS_TO, 'Client', 'client_id'), ); } public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->with = array('client'); $criteria->compare('task_id',$this->task_id); $criteria->compare('client_id',$this->client_id); $criteria->compare('name',$this->client->name); $criteria->compare('task',$this->task,true); $criteria->compare('start_date',$this->start_date,true); $criteria->compare('end_date',$this->end_date,true); $criteria->compare('complete',$this->complete); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); }

    Read the article

  • How to filter Many2Many / Generic Relations properly with Q?

    - by HWM-Rocker
    Hi, I have 3 Models, the TaggedObject has a GenericRelation with the ObjectTagBridge. And the ObjectTagBridge has a ForeignKey to the Tag Model. class TaggedObject(models.Model): """ class that represent a tagged object """ tags = generic.GenericRelation('ObjectTagBridge', blank=True, null=True) class ObjectTagBridge(models.Model): """ Help to connect a generic object to a Tag. """ # pylint: disable-msg=W0232,R0903 content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') tag = models.ForeignKey('Tag') class Tag(models.Model): ... when I am attaching a Tag to an Object, I am creating a new ObjectTagBridge and set its ForeignKey tag to the Tag I want to attach. That is working fine, and I can get all Tags that I attached to my Object very easy. But when I want to get (filter) all Objects that have Tag1 and Tag2 I tried to something like this: query = Q(tags__tag=Tag1) & Q(tags__tag=Tag2) object_list = TaggedObjects.filter(query) but now my object_list is empty, because it is looking for TaggedObjects that have one ObjectTagBridge with 2 tag objects, the first with Tag1 and the second with Tag2. I my application will be more complex Q queries than this one, so I think I need a solution with this Q object. In fact any combination of binary conjunctions, like: (...) and ( (...) or not(...)) How can I filter this correctly? Every answer is welcome, maybe there is also a different way do achieve this. thx for your help!!!

    Read the article

  • rails delete_all exception

    - by Sergei
    Hello, guys! I have some User model, Role model and Assignment model to manage role-based user system. Just like here . So, here some kind of code, to include roles into users form: <% for role in Role.all %> <%= check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role) %> <%=h role.name %><br /> <% end %> And all's working fine for new records and for editing records. But I just want to make possible to restrict deleting Assigment with id=1, cause this Assignment for default root user from migration, who must be admin anyway. Otherwise, I can lose my last admin. So I've tryed to add before_destroy to Assignment.rb model, but it doesn't work. I've noticed, that when I'm editing user and trying to remove his admin role(assignment), the server makes a delete_all method, not destroy method. So, does anybody know how to catch the deleting of Assignment with id=1 through this kind of code? Thanks in advance!

    Read the article

  • Accepts Nested Attributes For - edit form displays incorrect number of items ( + !map:ActiveSupport:

    - by Brightbyte8
    Hi, I have a teacher profile model which has many subjects (separate model). I want to add subjects to the profile on the same form for creating/editing a profile. I'm using accepts_nested_attributes for and this works fine for creation. However on the edit page I am getting a very strange error - instead of seeing 3 subjects (I added three at create and a look into the console confirms this), I see 12 subjects(!). #Profile model class Profile < ActiveRecord::Base has_many :subjects accepts_nested_attributes_for :subjects end #Subject Model class Subject < ActiveRecord::Base belongs_to :profile end #Profile Controller (only showing deviations from normal RESTFUL setup) def new @profile = Profile.new 3.times do @profile.subjects.build end end #Here's 1 of three parts of the subject output of = debug @profile errors: !ruby/object:ActiveRecord::Errors base: *id004 errors: !map:ActiveSupport::OrderedHash {} subjects: - &id001 !ruby/object:Subject attributes: exam: Either name: "7" created_at: 2010-04-15 10:38:13 updated_at: 2010-04-15 10:38:13 level: Either id: "31" profile_id: "3" attributes_cache: {} # Note that 3 of these attributes are displayed despite me seeing 12 subjects on screen Other info in case it's relevant. Rails: 2.3.5 Ruby 1.8.7 p149 HAML I've never had so much difficulty with a bug before - I've already lost about 8 hours to it. Would really appreciate any help! Thanks to any courageous takers Jack

    Read the article

  • Django - foreignkey problem

    - by realshadow
    Hey, Imagine you have this model: class Category(models.Model): node_id = models.IntegerField(primary_key = True) type_id = models.IntegerField(max_length = 20) parent_id = models.IntegerField(max_length = 20) sort_order = models.IntegerField(max_length = 20) name = models.CharField(max_length = 45) lft = models.IntegerField(max_length = 20) rgt = models.IntegerField(max_length = 20) depth = models.IntegerField(max_length = 20) added_on = models.DateTimeField(auto_now = True) updated_on = models.DateTimeField(auto_now = True) status = models.IntegerField(max_length = 20) node = models.ForeignKey(Category_info, verbose_name = 'Category_info', to_field = 'node_id' The important part is the foreignkey. When I try: Category.objects.filter(type_id = type_g.type_id, parent_id = offset, status = 1) I get an error that get returned more than category, which is fine, because it is supposed to return more than one. But I want to filter the results trough another field, which would be type id (from the second Model) Here it is: class Category_info(models.Model): objtree_label_id = models.AutoField(primary_key = True) node_id = models.IntegerField(unique = True) language_id = models.IntegerField() label = models.CharField(max_length = 255) type_id = models.IntegerField() The type_id can be any number from 1 - 5. I am desparately trying to get only one result where the type_id would be number 1. Here is what I want in sql: SELECT n.*, l.* FROM objtree_nodes n JOIN objtree_labels l ON (n.node_id = l.node_id) WHERE n.type_id = 15 AND n.parent_id = 50 AND l.type_id = 1 Any help is GREATLY appreciated. Regards

    Read the article

  • Validation on ManyToManyField before Save in Models.py

    - by Heyl1
    I have the following models: class Application(models.Model): users = models.ManyToManyField(User, through='Permission') folder = models.ForeignKey(Folder) class Folder(models.Model): company = models.ManyToManyField(Compnay) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') company = models.ManyToManyField(Company) What I would like to do is to check whether one of the users of the Application has the same company as the Application (via Folder). If this is the case the Application instance should not be saved. The problem is that the ManyToManyFields aren't updated until after the 'post-save' signal. The only option seems to be the new m2m_changed signal. But I'm not sure how I then roll back the save that has already happened. Another option would be to rewrite the save function (in models.py, because I'm talking about the admin here), but I'm not sure how I could access the manytomanyfield content. Finally I've read something about rewriting the save function in the admin of the model in admin.py, however I still wouldn't know how you would access the manytomanyfield content. I have been searching for this everywhere but nothing I come across seems to work for me. If anything is unclear, please tell me. Thanks for your help! Heleen

    Read the article

  • Sorting and Pagination does not work after I build a custom keyword search that is build using relat

    - by Roland
    I recently started to build a custom keyword search using Yii 1.1.x The search works 100%. But as soon as I sort the columns and use pagination in the admin view the search gets lost and all results are shown. So with otherwords it's not filtering so that only the search results show. Somehow it resets it. In my controller my code looks as follows $builder=Messages::model()->getCommandBuilder(); //Table1 Columns $columns1=array('0'=>'id','1'=>'to','2'=>'from','3'=>'message','4'=>'error_code','5'=>'date_send'); //Table 2 Columns $columns2=array('0'=>'username'); //building the Keywords $keywords = explode(' ',$_REQUEST['search']); $count=0; foreach($keywords as $key){ $kw[$count]=$key; ++$count; } $keywords=$kw; $condition1=$builder->createSearchCondition(Messages::model()->tableName(),$columns1,$keywords,$prefix='t.'); $condition2=$builder->createSearchCondition(Users::model()->tableName(),$columns2,$keywords); $condition = substr($condition1,0,-1) . " OR ".substr($condition2,1); $condition = str_replace('AND','OR',$condition); $dataProvider=new CActiveDataProvider('Messages', array( 'pagination'=>array( 'pageSize'=>self::PAGE_SIZE, ), 'criteria'=>array( 'with'=>'users', 'together'=>true, 'joinType'=>'LEFT JOIN', 'condition'=>$condition, ), 'sort'=>$sort, )); $this->render('admin',array( 'dataProvider'=>$dataProvider,'keywords'=>implode(' ',$keywords),'sort'=>$sort )); and my view looks like this $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'columns'=>array( 'id', array( 'name'=>'user_id', 'value'=>'CHtml::encode(Users::model()->getReseller($data->user_id))', 'visible'=>Yii::app()->user->checkAccess('poweradministrator') ), 'to', 'from', 'message', /* 'date_send', */ array( 'name'=>'error_code', 'value'=>'CHtml::encode($data->status($data->error_code))', ), array( 'class'=>'CButtonColumn', 'template'=>'{view} {delete}', ), ), )); I really do not know what do do anymore since I'm terribly lost, any help will be hihsly appreciated

    Read the article

  • ASP.NET MVC 2 - How do I use DropDownListFor ?

    - by SLC
    I have a simple model / view with things like Username, Password etc. and use helpers fine to hook it up. I now have a field called "NumberOfChildren". I want to store a number in it (int) and I want it render a dropdown box containing "None", "1", "2" etc. My thoughts would be that the model would have a list or a method that returns a list, so I can specify the values such as NumberOfChildren_List that I put the data into, and then DropDownListFor pulls that list and renders it, matching the value to the value of the item in the dropdown. However after spending about 30 minutes on trying to figure out how on earth it works, I gave up and decided to ask here. Any ideas? Edit: Here's some code... <%: Html.DropDownListFor(m => m.NumberOfChildren, new SelectList(Model.NumberOfChildrenListValues))%> and in the model [Required] [DisplayName("How many children do you have?")] public string NumberOfChildren { get; set; } public IEnumerable<string> NumberOfChildrenListValues { get { List<string> list = new List<string>() { "None", "1", "2" }; return list; } set { } } I get an object not set to instance of object error though. Ideas?

    Read the article

  • Can i change the view without changing the controller?

    - by Ian Boyd
    Pretend1 there is a place to type in a name:     Name: __________________ When the text box changes, the value is absorbed into the controller, who stores it in data model. Business rules require that a name be entered: if there is no text entered the TextBox should be colored something in the view to indicate baddness; otherwise it can be whatever color the view likes. The TextBox contains a String, the controller handles a String, and the model stores a String. Now lets say i want to improve the view. There is a new kind of text box2 that can be fed not only string-based keyboard input, but also an image. The view (currently) knows how to determine if the image is in the proper format to perform the processing required to extract text out of it. If there is text, then that text can be fed to the controller, who feeds it to the data model. But if the image is invalid, e.g.3 wrong file format invalid dimensions invalid bit depth unhandled or unknown encoding format missing or incorrectly located registration marks contents not recognizable the view can show something to the user that the image is bad. But the telling the user that something is bad is supposed to be the job of the controller. i'm, of course, not going to re-write the controller to handle Image based text-input (e.g. image based names). a. the code is binary locked inside a GUI widget4 b. there other views besides this one, i'm not going to impose a particular view onto the controller c. i just don't wanna. If i have to change things outside of this UI improvement, then i'll just leave the UI unimproved5 So what's the thinking on having different views for the same Model and Controller? Nitpicker's Corner 1 contrived hypothetical example 2 e.g. bar code, g-mask, ocr 3 contrived hypothetical reasons 4 or hardware of a USB bar-code scanner 5 forcing the user to continue to use a DateTimePicker rather than a TextBox

    Read the article

  • Open closed prinicple, problem

    - by Marcus
    Hi, I'm trying to apply OCP to a code snippet I have that in it's current state is really smelly, but I feel I'm not getting all the way to the end. Current code: public abstract class SomeObject {} public class SpecificObject1 : SomeObject {} public class SpecificObject2 : SomeObject {} // Smelly code public class Model { public void Store(SomeObject someObject) { if (someObject is SpecificObject1) {} else if (someObject is SpecificObject2) {} } } That is really ugly, my new approach looks like this: // No so smelly code public class Model { public void Store(SomeObject someObject) { throw new Expception("Not allowed!"); } public void Store(SpecificObject1 someObject) {} public void Store(SpecificObject2 someObject) {} } When a new SomeObject type comes along I must implement how that specific object is stored, this will break OCP cause I need to alter the Model-class. To move the store logic to SomeObject also feels wrong cause then I will violate SRP (?), becuase in this case the SomeObject is almost like a DTO, it's resposibility it not how to know to store itself. If a new implementation to SomeObject comes along who's store implementation is missing I will get a runtime error due to exception in Store method in Model class, it also feels like a code smell. This is because calling code will in the form of IEnumerable<SomeObject> sequence; I will not know the specific types of the sequence objects. I can't seem to grasp the OCP-concept. Anyone has any concrete examples or links that is a bit more than just some Car/Fruit example?

    Read the article

  • C++ member template for boost ptr_vector

    - by Ivan
    Hi there, I'm trying to write a container class using boost::ptr_vector. Inside the ptr_vector I would like to include different classes. I'm trying to achieve that using static templates, but so far I'm not able to do that. For example, the container class is class model { private: boost::ptr_vector<elem_type> elements; public: void insert_element(elem_type *a) { element_list.push_back(a); } }; and what I'm trying to achieve is be able to use different elem_type classes. The code below doesn't satisfy my requirements: template <typename T>class model { private: boost::ptr_vector<T> elements; public: void insert_element(T *a) { element_list.push_back(a); } }; because when I initialize the container class I can only use one class as template: model <elem_type_1> model_thing; model_thing.insert_element(new elem_type_1) but not elem_type_2: model_thing.insert_element(new elem_type_2)//error, of course It is possible to do something like using templates only on the member? class model { private: template <typename T> boost::ptr_vector<T> elements; public: void insert_element(T *a) { element_list.push_back(a); } }; //wrong So I can call the insert_element on the specific class that I want to insert? Note that I do not want to use virtual members. Thanks!

    Read the article

  • Post complex types to WebApi Client

    - by BumbleBee
    I am new to WebAPI. I have a MVC project and webApi project both reside under the **same solution**. Also, BLL Class library and DAL class library reside under the same solution. Earlier, my MVC project will talk to the BLL now I am trying to create a WebAPi project which stands in between MVC and BLL. Here is what I have come up with so far : I'm using the HTTPClient to post to a WebApi project. My post method on my controller accepts a single parameter (a model). StatsCriteria criteria = new StatsCriteria(); ...... var client = new HttpClient(); var response = client.PostAsJsonAsync("http://localhost:52765/api/reports", criteria).Result; ....... Here's the signature for my controller in Webapi [HttpPost] public CMAReportVM Reports([FromBody] StatsCriteria criteria) { var cmaReport = Service3.GetCMAReport(criteria.Mlsnums); //Create Map to enable mapping business object to View Model Mapper.CreateMap<CMAReport, CMAReportVM>(); // Maps model to VM model class var cmaVM = Mapper.Map<CMAReport, CMAReportVM>(cmaReport); reutn cmaVM; } // and here's my routing: config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } I am getting the following 405 : Method not allowed. As the WebAPI and MVC project both reside under same sloution I am not sure where/how to host my webapi.

    Read the article

  • ASP.NET MVC is not displaying the image

    - by Pinu
    <asp:Conte nt ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <%-- <h2>Notes</h2> <% Html.RenderPartial("~/Views/Shared/UserControl/Notes.ascx",Model.Notes); %> <br /> <h2>User Tracking Informtaion</h2> <% Html.RenderPartial("~/Views/Shared/UserControl/Tracking.ascx",Model.Log); %>--%> <div> <% for (int i = 1; i <= ViewData.Model.SelectedDocument.DocumentPages ; i++) { %> <br /> <img src="<%=DocuvaultMVC.Helpers.AppHelper.PDFUrl(ViewData.Model.SelectedDocument.DocumentID,i)%>" alt="Document" width="612" height="792" /> <%}%> <div> </div> </div> public static string PDFUrl(int id, int page) { return VirtualPathUtility.ToAbsolute("~/ViewDocument.aspx/" + id + "/" + page); }

    Read the article

  • OpenGL ES and real world development

    - by Mark
    Hi Guys, I'm trying to learn OpenGL ES quickly (I know, I know, but these are the pressures that have been thrusted upon me) and I have been read around a fair bit, which lots of success at rendering basic models, some basic lighting and 'some' texturing success too. But this is CONSTANTLY the point at which all OpenGL ES tutorials end, they never say more of what a real life app may need. So I have a few questions that Im hoping arent too difficult. How do people get 3d models from their favorite 3d modeling tool into the iPhone/iPad application? I have seen a couple of blog posts where people have written some python scripts for tools like Blender which create .h files that you can use, is this what people seem to do everytime? Or do the "big" tooling suites (3DS, Maya, etc...) have exporting features? Say I have my model in a nice .h file, all the vertexes, texture points, etc.. are lined up, how to I make my model (say of a basic person) walk? Or to be more general, how do you animate "part" of a model (legs only, turn head, etc...)? Do they need to be a massive mash-up of many different tiny models, or can you pre-bake animations these days "into" models (somehow) Truely great 3D games for the iPhone are (im sure) unbelievably complex, but how do people (game dev firms) seem to manage that designer/developer workflow? Surely not all the animations, textures, etc... are done programatically. I hope these are not stupid questions, and in actual fact, my app that Im trying to investigate how to make is really quite simple, just a basic 3D model that I want to be able to pan/tilt around using touch. Has anyone ever done/seen anything like this that I might be able to read up on? Thanks for any help you can give, I appreciate all types of response big or small :) Cheers, Mark

    Read the article

  • How to order search results by multiple fields?

    - by JustinRoR
    I am using Sunspot and Will_paginate for search in my application and don't how to have my search results start out with certain ordering conditions. The model I am searching is the UserPrice model and want my :price and :purchase_date in descending order or lowest price to highest and present date to past: class UserPrice < ActiveRecord::Base attr_accessible :price, :product_name, :purchase_date belongs_to :product # Sunspot configuration searchable do text :product_name do product.name end end end class SearchController < ApplicationController def index @search = UserPrice.search do fulltext params[:search] paginate(:per_page => 5, :page => params[:page]) end @user_prices = @search.results end end Even though I don't know how, I'm not sure if I would use Sunspot or Will_paginate to sort by order of price and purchase date. How would I achieve this though? Thank you. UPDATE I try to use the order_by method but not sure how the model would look now. class SearchController < ApplicationController def index @search = UserPrice.search do fulltext params[:search] paginate(:per_page => 5, :page => params[:page]) facet(:business_retail_store_id) facet(:business_online_store_id) order_by :price, :desc order_by :purchase_date, :desc end @user_prices = @search.results end end Not sure why having the following in my controller: order_by :price, :desc order_by :purchase_date, :desc I get the error: Sunspot::UnrecognizedFieldError in SearchController#index No field configured for UserPrice with name 'price' This doesn't make sense to me since I do have these fields inside of my UserPrice model and in my database. How do I fix this?

    Read the article

  • CodeIgniter: Where should a particular functionality go ?

    - by Samnan
    I have an application in codeigniter and a page needs to perform the following tasks 1 - controller decides which model to use based of the url and parameters 2 - controller loads the model and get the data from it 3 - controller formats the data in a particular format, depending on the items in it 4 - controller loads a common view, which will display the data (formatted data contains simple display fields) now there is a search page, which needs to do a text query against all of the possible text fields in database in all tables. It needs to show each type of data in its own formatted output on a single page as a list. The problem: The search controller can do the search, dynamically load model for each record type, and get the data from model. Problem comes when the data needs to be formatted. It looks that ideally the search controller should load another controller which will provide formatted data ... There is where it gets out of control ... My question is: What am I doing wrong? Is there any better way to do this? How would you do the same to solve the problem?

    Read the article

  • servicestack Razor view with request and response DTO

    - by user7398
    I'm having a go with the razor functionality in service stack. I have a razor cshtml view working for one of my response DTO's. I need to access some values from the request DTO in the razor view that have been filled in from some fields from the REST route, so i can construct a url to put into the response html page and also label some form labels. Is there anyway of doing this? I don't want to duplicate the property from the request DTO into the response DTO just for this html view. Because i'm trying to emulate an existing REST service of another product, i do not want to emit extra data just for the html view. eg http://localhost/rest/{Name}/details/{Id} eg @inherits ViewPage<DetailsResponse> @{ ViewBag.Title = "todo title"; Layout = "HtmlReport"; } this needs to come from the request dto NOT @Model <a href="/rest/@Model.Name">link to user</a> <a href="/rest/@Model.Name/details/@Model.Id">link to user details</a>

    Read the article

  • How do I call +class methods in Objective C without referencing the class?

    - by TimM
    I have a series of "policy" objects which I thought would be convenient to implement as class methods on a set of policy classes. I have specified a protocol for this, and created classes to conform to (just one shown below) @protocol Counter +(NSInteger) countFor: (Model *)model; @end @interface CurrentListCounter : NSObject <Counter> +(NSInteger) countFor: (Model *)model; @end I then have an array of the classes that conform to this protocol (like CurrentListCounter does) +(NSArray *) availableCounters { return [[[NSArray alloc] initWithObjects: [CurrentListCounter class],[AllListsCounter class], nil] autorelease]; } Notice how I am using the classes like objects (and this might be my problem - in Smalltalk classes are objects like everything else - I'm not sure if they are in Objective-C?) My exact problem is when I want to call the method when I take one of the policy objects out of the array: id<Counter> counter = [[MyModel availableCounters] objectAtIndex: self.index]; return [counter countFor: self]; I get a warning on the return statement - it says -countFor: not found in protocol (so its assuming its an instance method where I want to call a class method). However as the objects in my array are instances of class, they are now like instance methods (or conceptually they should be). Is there a magic way to call class methods? Or is this just a bad idea and I should just create instances of my policy objects (and not use class methods)?

    Read the article

  • Organising files and classes in XCode (iPhone application)

    - by pulegium
    It's a generic question and really a newbie one too, so bear with me... I'm playing with some iPhone development, and trying to create a simple "flip type" application. Nothing sophisticated, let's say on the flip side is a short application summary, bit like 'help' and on the main screen is a simple board game, let's say tic-tac-toe or similar. Now, XCode has generated me 'Main View', 'Flipside View' and 'Application Delegate' folders, with default template files in them. Now the question is where do I create appropriate 'MVC' classes? Let's say (V)iew classes are going to be the ones that have been automatically created. So the Flipside view class is responsible for generating text/images etc on the 'help' view. 'Main View' class is what draws the items on the table and updates the counters, etc. Where should I place the 'controller' class? And also, should it only be dealing with proxying only to the model? According to this the controller method is called from the view and manipulates the method classes. Similarly, the results from model are passed back to the view class by the controller issuing the calls to appropriate view methods. Similarly, where does the model class go? or should I just create a new folder for each, controller and model class files? What I'm after is the best practices, or just a short description how people normally structure their applications. I know it's very specific and also undefined... I came from Django background, so the way stuff is organised there is slightly different. Hope this makes sense, sorry if it's all bit vague, but I have to start somewhere :) And yes I've read quite few docs on the apple developer site, but trouble is that the documents are either going into too much detail about the language/framework/etc and the examples are way too simplistic. Actually, this leads me to the final question, has anyone know any good example of relatively complete application tutorial which I could use as a reference in organising my files?...

    Read the article

  • Should nested attributes be automatically deleted when I delete the parent record?

    - by brad
    I'm playing around with nested forms in attributes and have a model Invoice that has_many invoice_phone_numbers. I have the following line in my invoice.rb model file accepts_nested_attributes_for :invoice_phone_numbers, :allow_destroy => true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } } This does what it should and I can delete invoice_phone_numbers from the form by selecting their 'delete' checkbox. But when I delete an Invoice, I have noticed that the nested invoice_phone_numbers are not also deleted. This causes problems as rails seems to reuse id numbers in the Invoice model (Should it? Does this depend on the database? I'm using SQLite3) so phone numbers from previous invoices turn up in new invoices after they have been created. Anyway, my question is should the nested attributes be deleted when I delete the parent attribute? Is there a way to make this happen automatically as part of the nesting process or do I need to deal with this in my invoice model? If so, what is the best way to do this? I would try to go about this with a before_destroy callback but want to know if this is the best way to do this. Anyway, thanks.

    Read the article

  • ASP.NET MVC 2: HtmlHelpers, foreach?

    - by dcolumbus
    This one is new to me... I'm bringing in a Model that represents a list of items. Some items should be rendered as a number of checkboxes and radios. Others will be rendered in a list. Now I know how to foreach the items and spit them out manually... but I'd like to be able to check them against the Model that I have, making sure that at least one optios is selected/chosen. And obviously display the associated validation errors. This is how I am displaying the checkbox items manually: <ul> <% foreach (Corporate.Entities.DesignLayout.Tag tag in Model.DesignOptions.Items) { %> <li><input type="checkbox" /><%: tag.TagName %></li> <% } %> </ul> Two questions arise: 1) How do I check that list of checkboxes against my model? 2) How would I render the tag items with an HtmlHelper SelectList? Example: <%: Html.ListBoxFor(m=>m.DesignOptions, [don't know what I should put here]) %>

    Read the article

  • Sending data back to Controller Spring-MVC

    - by Umesh Awasthi
    I am not sure if this is a complex problem but as a starting person this seems a bit complex to me. I have an object based on which i need to show some values on the UI and let user select some of them, i need to send data back to another controller when user click on the submit button.Here is the structure of my data object public class PrsData{ private Map<String, List<PrsCDData>> prsCDData; } public class PrsCDData{ private Map<String, Collection<ConfiguredDesignData>> configuredDesignData; } public ConfiguredDesignData{ // simple fields } I have set the object in model before showing the view like model.addAttribute("prsData", productData.getPrData()); In the form i have following settings <form:form method="post" commandName="prsData" action="${addProductToCartAction}" > <form:hidden path="prsCDData['${prsCDDataMap.key}'] [${status.index}].configuredDesignData['${configuredDesignDataMap.key}'] [${configuredDesignDataStatus.index}].code"/> <form:hidden path="prsCDData['${prsCDDataMap.key}'] [${status.index}].configuredDesignData['${configuredDesignDataMap.key}'] [${configuredDesignDataStatus.index}].description"/> </form:form> This is what i have at AddProductToCartController public String addToCart(@RequestParam("productCodePost") final String code, @ModelAttribute("prsData") final PrsData prsData, final Model model, @RequestParam(value = "qty", required = false, defaultValue = "1") final long qty) On submitting the form i am getting following exception org.springframework.beans.NullValueInNestedPathException: Invalid property 'prsCDData[Forced][0]' of bean class [com.product.data.PrsData]: Cannot access indexed value of property referenced in indexed property path 'prsCDData[Forced][0]': returned null It seems like its trying to access the values on this controller while i am trying to send value to that controller and trying to create same object with selected values Can any one tell me where i am doing wrong and what i need to take care of

    Read the article

  • How to update attributes without valitation

    - by Brian Roisentul
    I've got a model with its validations, and I found out that I can't update an attribute without validating the object before. I already tried to add on => :create syntax at the end of each validation line, but I got the same results. My announcement model have the following validations: validates_presence_of :title validates_presence_of :description validates_presence_of :announcement_type_id validate :validates_publication_date validate :validates_start_date validate :validates_start_end_dates validate :validates_category validate :validates_province validates_length_of :title, :in => 6..255, :on => :save validates_length_of :subtitle, :in => 0..255, :on => :save validates_length_of :subtitle, :in => 0..255, :on => :save validates_length_of :place, :in => 0..50, :on => :save validates_numericality_of :vacants, :greater_than_or_equal_to => 0, :only_integer => true validates_numericality_of :price, :greater_than_or_equal_to => 0, :only_integer => true My rake task does the following: task :announcements_expiration => :environment do announcements = Announcement.expired announcements.each do |a| #Gets the user that owns the announcement user = User.find(a.user_id) puts a.title + '...' a.state = 'deactivated' if a.update_attributes(:state => a.state) puts 'state changed to deactivated' else a.errors.each do |e| puts e end end end This throws all the validation exceptions for that model, in the output. Does anybody how to update an attribute without validating the model?

    Read the article

< Previous Page | 143 144 145 146 147 148 149 150 151 152 153 154  | Next Page >