This was going to be a comment but it is so huge, so take it as a comment: It is possible that the oModel.read function is asynchronous so when you execute the code basically that happen is this: 1) You declare the variable as 0. 2) You execute read function....
ruby-on-rails,ruby-on-rails-4,models
Change it to this: has_many :businesses, -> { where(business_admins: { state: 'accepted'}) }, through: :business_admins Also see the Rails documentation....
You should use queryBuilder for best performance. Anyway if you alias your relation and stick to objects rather than arrays youre able to make some tricks like: // in users model $this->belongsTo( 'id', // local id 'Posts', // model relation 'user_id', [ // related id 'alias' => 'posts' // alias...
asp.net,forms,asp.net-mvc-5,models
I would say this is good example of using ViewModel here. I would suggest something like - Create ViewModel with the composition of the two classes public class AddWeightModel { [Required] [DataType(DataType.Text)] [Display(Name = "Stone")] public Nullable<short> Stone { get; set; } [Required] [DataType(DataType.Text)] [Display(Name = "Pound")] public Nullable<short> Pound...
If you want to set links/displays default value in DocLink instance based on trann field you can override model's save method. For example following code shows how to set t_link if it doesn't have a value: class DocLink(models.Model): trann = models.ForeignKey(Transaction) t_link = models.CharField(max_length=2000) t_display = models.CharField(max_length=1000) p_display = models.CharField(max_length=300)...
ruby-on-rails,associations,models
This is the use case that single table inheritance (STI) was designed for. When most of the values are shared between two models, STI can let you inherit both of them from another model. E.g.: class Review < ActiveRecord::Base; end class DishReview < Review belongs_to :dish end class OrderReview <...
php,laravel,eloquent,models,laravel-5
What you can do is: $model_object = Model::fill(['other_attributes' => 'other_values']); $model_object->guarded_field = 'value'; $model_object->save(); EDIT There is one more thing. If when using store/update you handle attribute in the code, you can safely add it to fillable attributes (you don't need to use it in guarded. $input = $request->input(); $input['guarded_field']...
android,listview,android-listview,models
Problem is getcount method it should be as below. @Override public int getCount () { return users.size(); } ...
php,laravel-4,models,relationships
In the TypeCost model hasMany relationship returns an object of type Collection, you have 2 options, using first or tour the object using foreach, also in the User model the relationship belongsToMany returns an object of type Collection, here you can see an example: {{ $type_cost->user->first()->username }} or @foreach($type_cost->user as...
The problem here seems to be name of the table class, respetively the name of the entity class, probably depends on your perspective. By default, the name of the corresponding entity class is guessed by using the singular table class name without the trailing Table, however Agpois doesn't inflect to...
Yes, you can use multiple modules for your models. Nothing in Flask or Python limits you to a specific module name or to just one module. If you are using Flask-SQLAlchemy, just make sure you import the db object (the SQLAlchemy instance that defines the Model object) in each. When...
django,django-admin,inline,models
Django doesn't support this (yet) but django-nested-inline can do the job.
A common trap in lme is that the default is to give raw residuals, i.e. not adjusted for any of the heteroscedasticity (weights) or correlation (correlation) sub-models that may have been used. From ?residuals.lme: type: an optional character string specifying the type of residuals to be used. If ‘"response"’, as...
django,inheritance,models,multi-table-inheritance,concrete-inheritance
First of all, inheritance has not a natural translation to relational database architecture (ok, I know, Oracle Type Objects and some other RDBMS support inheritance but django don't take advantage of this functionality ) At this point, notice than django generates new tables to subclasses and write lots of left...
Try this: def __unicode__(self): return unicode(self.cliente) ...
ruby-on-rails,key,models,rails-models
I tried above code and its working fine. I can save contact with group_id without any change in your code. Please check again. Are you getting group_id in params in controller?
django,models,filefield,imagefield
In the upload_to keyword you would need to provide a function that you will define, for instance: def path_file_name(instance, filename): return '/'.join(filter(None, (instance.info.mouja, instance.info.doc_type, filename))) class Image(models.Model): content = models.ImageField(upload_to=path_file_name) From Django documentation: Model field reference: This may also be a callable, such as a function, which will be called...
ruby-on-rails,rspec,entity-relationship,relationship,models
@blog => #<Blog id: 26, title: "user_blog_26"> @blog has an id assigned to it. So, that means its an existing record in blogs table with id = 26. @user.blogs.create(title: @blog.title) This line means that create a new record in blogs table with title same as that of @blog.title (i.e., user_blog_26)...
You must use request.POST.get() for getting the attributes that are send by the url, and send to the f = User(request.POST)the attributes for the model like u = User(name=name, subject=subject) #views.py def add_user(request): if request.method == 'POST': name = request.POST.get('name', '') subject = request.POST.get('subject', '') u = User(name=name, subject=subject) u.save()...
ruby-on-rails,ruby,ruby-on-rails-4,activerecord,models
FYI, I can confirm this is an issue with ActiveRecord and Ruby 2.2. I was using ActiveRecord 3.2 and since changing to the 3-2-stable branch, the issue is gone. I believe this is fixed now in 4.x branches. I have raised an issue for this at https://github.com/rails/rails/issues/18991.
Try using a django file instead of just an open file. from django.core.files import File ... f = open(FILENAME,'r') A=XML() A.xml.save(filename, File(f), save=True) A.save() ...
If you can reorganize your models, you can make use of models inheritance (https://docs.djangoproject.com/en/1.8/topics/db/models/#model-inheritance) Your Item model could have been a sub class of Shorten_Item, given that it only contains one extra field, the cl = CharField() You can keep Shorten_Item as it is, then make Item inherit from that...
ruby-on-rails,ruby,validation,methods,models
Here is the approach I would probably take: The comments to the right were added just to explain a little of what was going on. validate :duration private def duration length = (ends_at - starts_at) / 60 return if length.between?(30, 120) # bail out of validation if length falls between...
Use a values() command in your queryset. user_articles = Article.objects.filter(whopost=request.user.userprofile.id).values('whopost').order_by('-pub_date') ...
findOrCreateEach is deprecated; that's why it's not in the documentation. The best way to replicate the functionality is by using .findOrCreate() in an asynchronous loop, for example with async.map: // Example: find or create users with certain names var names = ["scott", "mike", "cody"]; async.map(names, function(name, cb) { // If...
python,django,migration,models
Amigo class did not defined on moment of declaration of Usuario class, so you cant use it in amigos field. From django docs: If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the...
You should move all the identical code to the app_shared application and import it from app_company1 and app_company2. If have separate tables in the DB is a requirement, then the inventory and transaction models should be defined as abstract in app_shared. app_company1 and app_company2 should create their own corresponding models...
ruby-on-rails,ruby,console,models
It looks like you have not yet run rake db:create This will "create" the databases on your PostgreSQL server. A step that you didn't have to do with SQLite, but Postgres requires it. As TK-421 said, make sure that your database.yml is configured for your OS and Postgres, not SQLite....
javascript,ember.js,controller,components,models
Computed properties aren't evaluated unless they are used. They are lazily evaluated. Using either of those properties will cause them to be evaluated and your logs will occur. http://jsbin.com/suheroya/1/edit Additionally it's important to know that the model itself isn't changing, so that computed property won't be called over and over....
php,mysql,codeigniter,models,controllers
try $data['quote']= $this->quotes_model->get_records(); $this->load->view('welcome_message', $data); and return your result from model:- return $query->result(); or return $query; ...
python,sql,django,foreign-keys,models
There are at least four approaches to the "both companies of type X and companies of type Y have contacts" problem: Two tables: Companies and Contacts. There is an enumerated property on Companies which has values X and Y, and every contact has one foreign key to a company. Three...
json,ember.js,autocomplete,models
Not sure I completely understand the question, but you can load arbitrary payloads into the the data store by calling pushPayload var pushData = { autocompleteObjects: [ {id: 1, value1: "foo", value2: "bar"} ] } store.pushPayload('autocompleteObject', pushData) Maybe in your app you could get for the JSON file and push...
ruby-on-rails,ruby,rails-activerecord,models,model-associations
Assuming your Job can only have one worker that is set when a Proposal is accepted, you'd want something like this: class Job < ActiveRecord::Base belongs_to :poster, class_name: 'User', foreign_key: 'poster_id' belongs_to :worker, class_name: 'User', foreign_key: 'worker_id' has_many :proposals, dependent: :destroy end class User < ActiveRecord::Base has_many :posted_jobs, class_name: 'Job',...
ruby-on-rails,validation,models
The easiest way will be to write a custom validation method, as described in the Active Record Validations Rails Guide. In your case, it might look something like this: class Degree < ActiveRecord::Base validate :validate_awarded_by_inclusion_dependent_on_degree_type # ... def validate_awarded_by_inclusion_dependent_on_degree_type valid_awarded_by_values = Degree.schools(degree_type) unless valid_awarded_by_values.include?(awarded_by) error_msg = "must be " <<...
Construct a Q object and use it in filter(): from viewer.models import Model1 from django.db.models import Q list1 = [ {'nut' : 'peanut', 'jam' : 'blueberry'}, {'nut' : 'almond', 'jam' : 'strawberry'} ] q = Q() for x in list1: q.add(Q(**x), Q.OR) query_results = Model1.objects.filter(q) Or, you can use operator.or_...
I guess you are looking for counter_cache The :counter_cache option can be used to make finding the number of belonging objects more efficient Consider these models: class Order < ActiveRecord::Base belongs_to :customer, counter_cache: true end class Customer < ActiveRecord::Base has_many :orders end With this declaration, Rails will keep the cache...
ruby-on-rails,ruby,relationship,models,belongs-to
I would do a model relation like this: user.rb has_many :reviews product.rb has_many :reviews reviews.rb belongs_to :user belongs_to :product # This does the magic for the multiple validation validates_uniqueness_of :user_id, :scope => :product_id, :message=>"You can't review a product more than once", on: 'create' As you can see, i will let...
Do the grouping in the backend of the view instead of the template. In your view, create a dictionary like this: sorted_groceries = { store1 : [item1, item2], store2 : [item3, item4], } which can be done with some code resembling this pseudo-code: sorted_groceries = {} for item in shopping...
java,lwjgl,models,collision,detection
You have a few options here. The easiest is to simply create an axis-aligned bounding box (AABB) around the object; this can be done algorithmically by simply finding the minimum and maximum values for each axis. For some applications this will work fine, but this obviously isn't very precise. It's...
@products = Product.order("count(votes) DESC") If you have not votes column then use: @products = Product.all.sort { |a, b| b.votes.count <=> a.votes.count } ...
2: if you do virtual navigation properties then will work lazy load value of this property: public class Book { //... public int AuthorId { get; set; } public virtual Author Author { get; set; } } It work: EF create proxy to your entity (Book) and overrides navigation property...
you can get inspired from django's admin log from django.contrib.admin.models import LogEntry or use it if it matches your requirements. Checkout this
php,laravel-4,models,extends,extending-classes
The easiest way is to fork the package on github, make the changes to the package yourself, then pull in your custom package on composer (instead of the original package). This way you maintain control over your changes on the other package. The specific method for pulling in your fork...
mysql,ruby-on-rails,models,database-migration
When you use belongs_to in Rails, you're saying that the model containing the belongs_to has the foreign key to the other object. In this case, you've placed the foreign key, role_id on the User model. Therefore, the User model should contain the belongs_to :role, and the Role model should contain...
It looks like (re-reading your post it's not 100% clear) what you want is a partial application. Good news, it's part of Python's stdlib: import os from functools import partial def generic_upload_to(instance, filename, folder): return os.path.join(instance.name, folder, filename) class Project(TimeStampedModel): name = models.TextField(max_length=100, default='no name') logo = models.ImageField( upload_to=partial(generic_upload_to, folder="logo")...
As of writing this it does NOT support these requests, however their is a pull request https://github.com/balderdashy/waterline/pull/525 You can use policies to do this in the mean time....
"Storage" that holds 2 "StorageType" That means Storage can have many StorageType and StorageType can have Storages. Make a new ManyToMany Field in the storage. class Storage(models.Model): storage_types = models.ManyToManyField(StorageType) def __unicode__(self): return str(self.id) class StorageType(models.Model): tripa = 'Tripa' portada = 'Portada' type_choice = ( (tripa, 'Tripa'), (portada, 'Portada'),...
ruby-on-rails,ruby,ruby-on-rails-4,activerecord,models
I don't really understand the difference between Company and Organization. I'm assuming Company and Organization have no relation to each other. So you can just union the two sets. <% companies_and_organizations = (Company.all.pluck(:name) + Organization.all.pluck(:name)).sort %> <%= f.text_field :company_name, data: {autocomplete_source: companies_and_organizations}, required: true %> Then I assume you only...
ruby-on-rails,rake,models,migrate
There is a typo here: it is db:migrate (instead of bd:migrate). Also, rake does not create models. To create models along with migrations, use rails generate model MyModel. On the other hand, if all your tables are created using migrations, then just create the model files manually in the app/models...
You are looking for an Extra fields on many-to-many relationships Your code should look like this: class Bank(models.Model): name = models.Charfield() money = models.IntegerField() members = models.ManyToManyField(StockShares, through='Sale') class StockShares(models.Model): name = models.Charfield() price = models.Charfield() class Sale(models.Model): bank = models.ForeignKey(Bank) stockshares = models.ForeignKey(StockShares) date = models.DateField() Maybe quantity should...
There is no need to add the trc field, because it will already exist. Check out the very similar example in the django docs on multi-table inheritance: If you have a Place that is also a Restaurant, you can get from the Place object to the Restaurant object by using...
json,backbone.js,collections,models
Remove the id from the defaults altogether. The id is a representation of id's that are present in the back end; if the id on a Backbone model is present, then the library assumes that you are working with a model that exists in the back end (and has a...
class Language(models.Model): name = models.CharField(max_length=100) class Word(models.Model): name = models.CharField(max_length=100) language = models.ForeignKey(Language, related_name='language_words') #... class Translation(models.Model): word = models.ForeignKey(Word, related_name='word_translations') translation = models.CharField(max_length=100) from_language = models.ForeignKey(Language, related_name='language_translations') in_language = models.CharField(max_length=100) # stage performances english_language =...
python,django,django-views,models
You need to pass the list to template from the view. In your code, the variable doctor is not defined in the template, so it doesn't show anything. Change your view to pass doctlist as def allDocs(request): return render(request, 'meddy1/doclistings.html', {'doclist': Doctor.objects.all()}) Update template to use doclist to show each...
I think you are looking for rails built-in helper fields_for. See the docs here....
You could make a custom getter... class User < ActiveRecord::Base def username self[:username].titleize end end If you want it only on reads for views but not on reads for edits then you might be better off using a decorator. https://github.com/drapergem/draper...
ruby-on-rails,associations,models,nesting
Shallow Nesting "One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions." See Rails Guide on Routing Section 2.7.2 Shallow Nesting for more information In...
ruby-on-rails,ruby,ruby-on-rails-4,models
So, I went and looked at code of mine that does a similar function. Here's what my create method looks like. This is creating a Student with assignment to Student Groups in a school setting (I didn't use "class" since Ruby wouldn't like that). def create @student = Student.new(student_params) if...
I wouldn't complicate the matters on a frontend with a new model / api / controller (JobFavourite) in this particular case unless it is absolutely necessary. I would make "favourite" a filter on Job's controller. So, on a filtered job list view you call GET /jobs?favourites=true to get only favourited...
ruby-on-rails,validation,models
It might be easier to just make an explicit validator method for this: class Foo < ActiveRecord::Base validate :ip_address_uniqueness, on: :create # ... def ip_address_uniqueness existing = Foo.where(impressionable_id: self.impressionable_id) .where(ip_address: self.ip_address) .where(created_at: Time.current.all_day) errors.add(:ip_address, 'cannot be used again today') if existing end end ...
From what I can deduce, you have a Friendship Eloquent Model attached to the friendship pivot table. The problem with that is that Eloquent doesn't work with composite primary keys, so there's no real way of doing that. You should have a look at the Laravel Eloquent Docs to see...
YourModel.objects.filter(B='something').delete() or for empty foreign key: YourModel.objects.filter(B__isnull=True).delete() ...
ruby-on-rails,ruby,activerecord,models
As per the error private methodfeed' called for #`, You are calling a private method named feed on an instance of Usermodel. In order to get the below code working @feed_items = current_user.feed.paginate(page: params[:page]) Make sure that method feed in User model is not under private section. Just remember, a...
ruby-on-rails,ruby,ruby-on-rails-4,widget,models
It's impossible to define this as an association. instead, you can define your own method: def widgets headers + galleries end but remember that the result of this method will be simple Array, not an ActiveRecord::Relation - so you won't be able to call AR scope methods on this. ...
I solved this issue when deleting the old migrations files that django created.
ruby-on-rails,model-view-controller,models,controllers
You can just create a method in the Loan model make_payment(amount) and reduce the amount from the total loan amount. I would advice you to maintain a log of payments in order to keep track of them later. Create a Payment model that belongs to the Loan model....
javascript,angularjs,loops,angularjs-scope,models
To start, you should move the implementation details outside of the view (i.e., you shouldn't be directly setting model.attack = power.attack in the view, that should be at least one level deeper, in the controller). With that, moving this to the controller will resolve your issue itself. Your view can...
python,django,django-models,models
You can create two applications, one for Users and one for Countries. Then put the User model in the Users app and the Country model in the Countries app. Then in a third app you can import both as you need them: from countries.models import Country from users.models import User...
I've solved the issue importing the application module as it follows: from person import models as person_class And then, in the field of the OneToOneField: person = models.OneToOneField(person_class.Person, verbose_name=_(u"Person"), related_name="person") ...
In Your form You could use: <%= link_to @user.name, @user %> because You already wrote in UsersController: ... @user = User.find(custom_id: params[:id]) ... ...
Simple Linq New List<AccommodationImageModel> new = compareList.Where(c=>c.id==0).ToList(); To be deleted List<AccomodationImageModel> deleted = masterList.Where(c => !compareList.Any(d => d.id == c.id)).ToList(); To be updated List<AccomodationImageModel> toBeUpdated = masterList.Where(c => compareList.Any(d => c.id == d.id)).ToList(); ...
python,django,django-queryset,models
I may be wrong, but i feel like your model structure is not normalized. You have a M2M relation between Player and Item via Slots. Consider the following model structure: from django.db import models from django.contrib.auth.models import User class Slot(models.Model): #e.g. main_hand, off_hand, head, ... , feet name = models.CharField(max_length=255)...
python,google-app-engine,models,app-engine-ndb
Although poorly documented, there is an introspection API for NDB models; simply use the name of the configuration option with an underscore prefixed: Contact._properties['name']._required is the value of the required option. The underscores do not signify 'privacy' here but are used to avoid clashing with names from the model itself...
javascript,jquery,ruby-on-rails,controller,models
You are most likely trying to use javascript variable in ruby. This kind of confusion is one many reasons to avoid intermingling your client side and server side code. Instead you can use data attributes and ajax to pass data to javascript. <div id="map-canvas" data-initlat="<%= @initlat %>"></div> Or another example:...
python,statistics,models,statsmodels
I don't see any problem. Generalized Linear Models are Maximum Likelihood models, if the scale is the one implied by the family. statsmodels.GLM doesn't currently implement Quasi-Likelihood methods where the scale can deviate from those of the underlying family, e.g. overdispersed Poisson, so the Likelihood Ratio test can be applied....
laravel,laravel-4,routing,models,relationships
in the simplest form, in your MessagesController in the show method, you can add an additional parameter to your query and get the record where message_id = the paramater from the url and the user_id on that message is the authenticated user's ID.... do something like $message = App\Message::where('id', '=',...
table.objects.all() is a django.query.QuerySet object. When you run x[0], you actually calls its __getitem__ method. You can find its implementation at github. Below is a simplified version. I only remove the safety check and slice code. def __getitem__(self, k): """ Retrieves an item or slice from the set of results....
If I understand well your question. You want to make some Java to SQL mapping which basicly do JPA(Hibernate) Hibernate is ORM tool "Object-relational mapping" Just check @Entity and you will find what you need eg. HERE....
python,django,django-models,models
If I understood you right, this is my solution. Any call to queryset api prints caller stack. import inspect from django.db import models from django.db.models import Manager class LogManager(Manager): def get_queryset(self): print inspect.stack() # in py3.4 the [2] element was the actual caller outside Manager so I used [2:] return...
validation,module,yii2,models,yii2-advanced-app
I guess this is what you want. First use the property "checked" in the whenClient of the input field to get if the checkbox is checked or not. The hidden field of the checkbox is not an issue. The whenClient in hero_linked (checkbox) is used to validate the hero_link (textinput)...
You will need to validate the statuses count for each person in the clean method. from django.db import models from django.core.exceptions import ValidationError class Status(models.Model): name = models.CharField(max_length=30) class Person(models.Model): name = models.CharField(max_length=30) status = models.ManyToManyField(Status) def clean(self): # check person status count if self.status.all().count() > 3: raise ValidationError("Person can...
Well you could add a where like for every column in the table: $columns = Schema::getColumnListing('users'); $query = User::query(); $search = Input::get('search'); foreach($columns as $column){ $query->orWhere($column, 'like', '%'.$search.'%'); } $users = $query->get(); ...
php,sql-server,sorting,yii,models
to do such thing you need SQL statement like this. SELECT status FROM table_name ORDER BY CASE name WHEN 'New data' THEN 1 WHEN 'open data' THEN 2 WHEN 'pending data' THEN 3 END; in Yii model: $criteria = new CdbCriteria(); $criteria->order ="CASE Column_name WHEN 'New data' THEN 1 WHEN...
ruby-on-rails,database,postgresql,models
On the Rails side, you could use a custom validator to ensure an Animal's father is a male (and mother a female). I don't know much about your specific models, but here's an example: class Animal < ActiveRecord::Base belongs_to :father, :class_name => "Animal" belongs_to :mother, :class_name => "Animal" validate :ensure_mother_and_father_are_correct_gender...
It depends on whether you have many fields specific to agenda (not to month). If you do, it's better to have one separate model for agenda. BTW, It seems user and agenda are many-to-many relationship. In this case, you need one intermediate model between user and agenda. ...
ruby-on-rails-4,associations,models
Please try like this: <% @artists = Artist.where(name: "Test").first %> <% @concertTest = @artists.concerts %> Note:- where will return Active record relation array....
ruby-on-rails,ruby,associations,models
Shouldn't you be using belongs_to? class RealmType < ActiveRecord::Base has_many :realms, foreign_key: "realm_type_id" end class Realm < ActiveRecord::Base belongs_to :realm_type end ...
php,symfony2,doctrine2,models,entities
I've come up with a solution for this issue, and it does involve traits. What I'm doing is basically trying to create several variations of a table. The relationship between the reviews is more horizontal than vertical (One type of review might have ratings, another one a video, another both)....
ember.js,controller,ember-data,models
To set properties on a controller not affiliated directly with a route by naming convention refer to the following jsbin. http://emberjs.jsbin.com/gugajaki/3/edit App = Ember.Application.create(); notifications = [ {seen: false, message: "tornado siren!!"} {seen: true, message: "Omg lol security breach"} {seen: false, message: "BFF Rite?"} {seen: false, message: "steve kane 4...
entity-framework,asp.net-mvc-5,models
If you are using EF Code First (not specified in your question), you will need to change the ContactId property name to ContactsId to match the convention of ClassName + Id in order to define the key for your Contacts entity type. See the MSDN Code First Conventions: http://msdn.microsoft.com/en-us/data/jj679962.aspx...
php,laravel,model-view-controller,laravel-5,models
As you can see in the error, it tries to find the model in the same namespace as your controller: FatalErrorException in MyersController.php line 20: Class 'App\Http\Controllers\Myer' not found. In the Model, you can see it's in namespace App. So either put use App\Myer; in the top of your controller...