FAQ Database Discussion Community


How to show users how many downloads they made Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller,model
In my app when the buyer buys something from the seller, the points from the buyer goes to the seller. This is the logic in the controller (gig = is the product) def downloadpage ActiveRecord::Base.transaction do if current_user.points >= @gig.pointsneeded current_user.points -= @gig.pointsneeded @gig.user.points += @gig.pointsneeded current_user.save @gig.user.save redirect_to @gig.boxlink...

Paperclip dimension validation error in Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller,model
I want in my app user to be able to upload files with at least width:800px and height: 550px I created in app/models/dimensions_validator.rb file and the code class DimensionsValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path) width = options[:width] height = options[:height] record.errors[attribute] << "Width must be at...

Python, DB and models

python,database,model
I am writing some python gui app (PySide to be exact) and I am using my own class to handling DB. What's the correct way to use models? Currently I have something like this: class DB(object): def __init__(self, dbfile): some db connect work def updateEntry(entryid): some update query etc def...

Unable to combine date and time in c# mvc model

c#,asp.net-mvc,model
I have a model like this. [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true), Display(Name = "Start Date")] public DateTime? StartDate { get; set; } [DataType(DataType.Time)] [DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true), Display(Name = "Start Time")] public DateTime? StartTime { get; set; } I want to combine them into 1 variable....

Confused about the behavior of returned object

ruby-on-rails,ruby,model,find-by-sql
After firing a Model.find_by_sql as; data = Setup::Type.find_by_sql ["SELECT value FROM table WHERE type_cd = 'print_format' AND subtype_cd = 'schedule_print_format'"] The object is returned as; #<Setup::Type:0x60c42f0> #<Setup::Type:0x60c4140> #<Setup::Type:0x60c3f90> On using the 'inspect' function on data,it retruns [#<Setup::Type value: "SalesReceipt_Bhindi_sch.rpt">, #<Setup::Type value: "SpecialOrder_Bhindi_sch.rpt">, #<Setup::Type value: "ReturnReceipt_Bhindi_sch.rpt">, #<Setup::Type value:...

Validation failed: User can't be blank

ruby-on-rails,model,devise
All, I am getting the error: Validation failed: User can't be blank. I am getting this error when I save down a comment. Can anyone point me in the right direction possibly? The comments controller class CommentsController < ApplicationController def create @topic = Topic.find(params[:topic_id]) @post = @topic.posts.find(params[:post_id]) @comment = @post.comments.new(params.require(:comment).permit(:body))...

Setting an XML attribute in the model

c#,xml,serialization,model,xml-attribute
I need to set an attribute in my XML. I require the following: <finAccount version="1.00"> Here is my model so far [XmlAttribute("version")] [XmlType("finPOWERConnect")] public class ApplicationData { public List<Account> Accounts; } [XmlType("finAccount")] public class Account { //Account stuff } The following function serialises my object to xml using the above...

Fuelphp ORM unexpected results when adding to model property

php,orm,model,increment,fuelphp
I have a model that tracks views. It's a very basic model as you can see below. There are currently only 2 methods. One queries the database, and one to add to the views table. The function that checks the table returns either a view object, or null. It's a...

Can the constants be defined inside a model file of a framework in PHP?

php,model-view-controller,model,constants,phpfox
I'm using PHPFox framework. I've to define two constants which would be used only by two functions present within that model class file. So can I define the constants at the beginning of this model class file or would it cause any issue or is it against the coding standards?...

phalcon load classes from directory

php,model-view-controller,model,phalcon,autoloader
I have a problem with loading "Model" classes from directory in phalcon framework 2.0. I can't use namespaces now, because project is migrating step by step from ZF1, and Model classes has many dependencies with themselves. If I register namespaces for every directory - loader works great, but I need...

How to use: $this->Auth->user('id') in a model? Cakephp 3.0

cakephp,authentication,model,cakephp-3.0
I've been working on the skinny controller fat model way. Before, I used this in my controller: $this ->find('all') ->contain(['Declarator']) ->where(['user_id' => $this->Auth->user('id')]) ->order(['Declarations.created' => 'DESC']); However, $this->Auth->user('id'), doesn't work in a model. What other way is there to get the id from the authenticated user in a model?...

How do you save an array of arrays in a mongoid model?

ruby-on-rails,model,mongoid
I have a response from an api that I need to save in my model which is using mongoid. I believe the response is an array of arrays and I cant seem to save it as an array or hash. Here is a sample of the response. Does anyone know...

How to link to another user in Django template

django,templates,hyperlink,model,slug
I want to link to another user to show for example their public activities. But I don't know how to link it via template. This is my user profile model: class UserProfile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=64) location = models.CharField(max_length=64, default='Tehran') picture = models.ImageField(upload_to='profile_images', blank=True, default="/user_image/user_default.png") slug = models.SlugField()...

Contact form: error on seeding and error messages of the form don't work properly

ruby-on-rails,ruby,ruby-on-rails-4,model,seeding
The app I'm building includes a contact form. On seeding it generates an error message that I don't understand: ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR: null value in column "name" violates not-null constraint DETAIL: Failing row contains (1, null, null, null, 2015-06-06 13:43:12.339477, 2015-06-06 13:43:12.339477). : INSERT INTO "messages" ("created_at", "updated_at") VALUES ($1,...

How to get header and data from Models in Python?

python,django,model,xlsx,openpyxl
Following this example (for openpyxl): from openpyxl.workbook import Workbook header = [u'Name', u'Email', u'Mobile', u'Current location',] new_data = [[u'name1', [email protected]', 9929283421.0, u'xxxx'], [u'name2', [email protected]', 9994191988.0, u'xxxx']] wb = Workbook() dest_filename = 'empty_book.xlsx' ws1 = wb.active ws1.title = "range names" ws1.append(header) for row in new_data: ws1.append(row) wb.save(filename = dest_filename) I have...

Rails select_tag will not access belongs_to relation

ruby-on-rails,ruby,model,html-select,belongs-to
I am trying to do a select_tag "employee_compensation_benefits_selection", options_from_collection_for_select(@employees, "id", "entity.name", "1") but entity.name wont work throws an undefined method `entity.name'. "entity" belongs to another model. through an entity_id class Employee < ActiveRecord::Base include UUIDHelper belongs_to :entity has_one :status has_many :restdays has_one :regular_work_period validates_presence_of :entity end require 'file_size_validator' class Entity...

Paperclip allow users to upload pictures of 800x500 and above in Rails 4

ruby-on-rails,validation,ruby-on-rails-4,model-view-controller,model
I created a file entitle in my models called dimensions_validator.rb class DimensionsValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) if record.send("#{attribute}?".to_sym) dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path) width = options[:width] height = options[:height] record.errors[attribute] << "Width must be at least #{width}px" unless dimensions.width = width record.errors[attribute] << "Height must be at least #{height}px" unless...

When should I use ViewBag/model?

c#,model,asp.net-mvc-5,viewbag
I think that using ViewBag is faster than model. My example is: In the action: public ActionResult MyAction() { ViewBag.Data = (from m in myDatabase.myTable select m).ToList(); } In the view: @foreach(var item in ViewBag.Data) { <tr> <td>@item.myColumn</td> </tr> } By using model: [Table("tbl_mytable")] public class MyTable() { public int...

Defining relationships across Multiple Models - Django

python,mysql,django,model,foreign-keys
I have the following relationship between three Django models: class TestCase(models.Model): ''' Define the testcase model. A testcase is a python Class which contains a set of tests ''' name = models.BinaryField(blank=False) filename = models.BinaryField(blank=True) run_flag = models.IntegerField(default=0) run_as_root = models.BooleanField(default=0) num_tests = models.IntegerField(default=0) testsuite = models.ForeignKey(TestSuite) def __str__(self): return...

Getting error when showing the purchases of the user,when showing the product he bought i get an error for product image and title

ruby,database,ruby-on-rails-4,model-view-controller,model
This is the relationship i have between User,Gig(product),and Purchase table that records the purchase. class User < ActiveRecord::Base has_many :gigs has_many :purchases, foreign_key: 'buyer_id' has_many :sales, foreign_key: 'seller_id', class_name: 'Purchase' end class Gig < ActiveRecord::Base has_many :purchases has_many :buyers, through: :purchases has_many :sellers, through: :purchases end class Purchase < ActiveRecord::Base...

Custom validation message (in model file) that includes a path not working

ruby-on-rails,ruby,ruby-on-rails-4,heroku,model
In the user model file I have included: validates :email, uniqueness: { case_sensitive: false, message: "You can reset your password " + link_to("here", new_password_reset_path) } On loading the page on the development server, this generates the error: undefined local variable or method `new_password_reset_path' for #<Class:0x007f4d36863460> The alternative code below has...

Delete single model from collection in Backbone.View

javascript,backbone.js,collections,model
var PlayersView = Backbone.View.extend({ collection: players, //collection of players el: "#playersList", //I bind to the class render: function () { this.$el.html(""); for (var i=0; i<this.collection.size(); i++) { var player = this.collection.at(i); this.$el.append("<li "+"value='"+player.get("id")+"'>"+player.get("names")[0]+" "+player.get("surnames")[0]+" <a href='#' class='edit'>[edit]</a>"+"</li>"); } //what I render is in the picture below return this; }, events:...

Rails - is it possible to have a shortcut within a model for its nested attributes?

ruby-on-rails,model,nested
This might be a stupid question but it's wracked my head for a while... So.. I have 2 models: (1) user, and (2) profile. The profile is associated to user via the following relationships: (1) user has_one :profile (2) profile belongs_to user It is the standard relationship for user and...

Changing nav-bar links according to whether a user has created a profile or not (RoR)

ruby-on-rails,ruby,if-statement,model,devise
I'm making a rails app and have created a simple navbar that works fine. I have set up devise and created a profile model which I would like users to create after they sign up, and (I believe) I have correctly made the necessary associations. As a new user signs...

Laravel 5 How to Pass 2 Models to a Form

php,forms,laravel,model,laravel-5
I have form and i am using form model binding. My form is {!! Form::model($vehicle,['url' => '/pages/store']) !!} <table style="width:650px; margin-left: 4px;" > <tbody> <tr> <td>ID</td> <td>Model</td> <td>Brand</td> <td>License Plate</td> </tr> <tr> <td>{!! Form::text('id' ,null , ['readonly'], ['class' =>'textboxlong form-control', 'style'=>'height:23px;']) !!}</td> <td>{!! Form::text('model' ,null ,['class' =>'textboxlong...

Yii2: How to add validation rules to the model class dynamically?

php,reflection,model,yii2
As per the Yii2 docs validation rules can be applied either to the implicit properties (table fields) or to the userDefined properties. Is there a way to create validation rules for the properties which are dynamically added to the model class ? For example: Let there be model class named...

Rails tagging fail when printing the name of the tag

ruby-on-rails,view,model,tagging
I am busy building a tagging system in RoR. This system I've coded according to: http://tutorials.jumpstartlab.com/projects/blogger.html#i3:-tagging Now when I print out tag.name it works but I also get what looks like the entire tag_list as an object printed out directly next to it. The view render in my browser clarifies...

Push value to model when created - Rails

ruby-on-rails,ruby,forms,model,controller
I am trying to set the inputter_id value automatically to the id for for the inputter_type corresponding to "Medical team" in a form if the user is a current_clinician: def create esas_assessment_params = params.require(:esas_assessment).permit(:patient_id, :clinician_id, :time, :year, :month, :day, :inputter_name, :inputter_id, :pain, :pain_comment, :tiredness, :tiredness_comment, :drowsiness, :drowsiness_comment, :nausea, :nausea_comment, :lack_of_appetite,...

How do you send data to controller with ajax.beginform?

ajax,asp.net-mvc-4,razor,model-view-controller,model
This is my method on controller "sale" [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Models.account account) { Models.sale creaventa = new Models.sale(); //creaventa.account = cliente; creaventa.createdon = DateTime.Now; creaventa.idaccount = account.id; creaventa.modifiedon = DateTime.Now; creaventa.status = 0; context.sales.Add(creaventa); context.SaveChanges(); // return "venta creada"; return View(); } and this is the partial view @model...

Rails Undefined Method in an unknown way

ruby-on-rails,ruby,methods,model,undefined
I cloned a project that runs just fine. I did the bundle install, bundle update, db:create, db:migrate, and whatnot. Now when I run http://localhost:3000/orders/new it returns a NoMethodError in Admin::Orders#new I have this as part of my code under model/admin/area.rb has_many :admin_accounts, :class_name => 'Admin::Account' validates :name, :presence => true...

Creating a status attribute for a model

ruby-on-rails,ruby,activerecord,model,attributes
I want to create a status attribute for my Taskmodel that would indicate where it is in a three part progress in this order: open => in-progress => complete. It would work in a way similar to how an Amazon package is delivered: ordered => shipped => delivered. I was...

Select Query from two tables in code igniter

mysql,sql,codeigniter,table,model
i have 2 tables Events and Registration Events Fields: EventID and EventName Registration Field: MemberID and Name i want to pull the EventName and the Name- of the person. how do i do this with a model? the code i have Model function getAll() { $query = $this->db->get('tblRegistration'); if( $query->num_rows()...

Database Model to Represent Families, Households, and Relationships

database,model,relationships
Here's my situation. I am building a database to track relationships between people and households. Typically, everything is tied to a "head of household". I am trying to avoid this as it creates problems when people move (i.e. brother finally gets a job and moves out) or families break up...

Elasticsearch data model

data,elasticsearch,model,nested,parent-child
I'm currently parsing text from internal résumés in my company. The goal is to index everything in elasticsearch to perform search on them. for the moment I have the following JSON document with no mapping defined : Each coworker has a list of project with the client name { name:...

iOS - Saving logged in user info

ios,swift,caching,model
So in my app I have a master view controller which checks whether or not NSUserDefaults.standardUserDefaults().objectForKey("userLoggedIn") == nil or not. If it's nil, it presents the authentication view controller (login ,register, etc.). Otherwise, the app is initialized. My question is - should I be storing user information? I'm not talking...

Rails 4 - Allow password change only if current password is correct

ruby-on-rails,authentication,model,passwords,bcrypt-ruby
In my app, users can edit their profile information. On the edit profile form, the user can make changes to all fields (name, title, and more). On this same form are three fields: current_password, password, and password_confirmation. I am using bcrypt's has_secure_password feature for password authentication. I am NOT using...

How to get the value from model to controller

php,codeigniter,model,controller
model This is my model.using last query I get value in the model,but I don't get the value in the controller class Login_model extends CI_Model { function __construct() { parent::__construct(); } public function email() { $this->db->select('email'); $this->db->from('change_password'); $result=$this->db->get(); return $result; } } controller class Login extends CI_Controller { function __construct()...

Rails ActiveRecord model scope with joins on has_many associations

ruby-on-rails,ruby,activerecord,model,active-record-query
I’m currently setting up a scope in my Rails model to be used by ActiveAdmin. The scope I want to build should find every Job that has a survey_date in the past, with a Job.survey present, and no Job.quotes present. Here is an abbreviated version of my Job model: has_many...

Using Spring's WebApplicationContext JUnit framework - How do I check the field value of an object set in my model?

spring,spring-mvc,junit,model
I’m using Spring 3.2.11.RELEASE and JUnit 4.11. In my unit tests, how do I check the value of a field of an object included in my model? In my unit tests, I have calls like: @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration public class MyControllerTests { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; … @Test...

Conceptual Modelling - Is my drawing correct ?

model,uml,conceptual,3d-modelling,graph-modelling-language
I have a exam tomorrow and we have gotten a sample exam, but since there are no answers to this sample exam, Id thought Id ask here. So here we go, this is one of the questions Im not sure if ive done correctly: Q: Draw a conceptual model describing...

Prevent upvote model from being called for every comment

ruby-on-rails,ruby,database,performance,model
I have three models: User, Comment and Upvote. User-to-Comment has a one-to-many relation, Comment-to-Upvote has a one-to-many relation and User-to-Upvote has a one-to-many relation. I want to do something similar to the upvoting done on Stackoverflow. So when you upvote/downvote the arrow will highlight and remain highlighted even if you...

How does a form field in the view become associated with an object in the model?

c#,asp.net-mvc,view,model
This is a two part question. First, I understand that if use this in my Model: [Required(ErrorMessageResourceType = typeof(Resources.CustomerSatisfactionSurvey), ErrorMessageResourceName = "Page1Question1Required")] public int? LikelyToReturn { get; set; } And then this in my View: @for (var c = 0; c < 11; c++) { @Html.RadioButtonFor(model => Model.LikelyToReturn, @c) }...

Set Modify and Create DateTime in ASP.Net MVC

c#,asp.net,asp.net-mvc,datetime,model
I am trying to create my own CMS Blog for education purposes, and nearly every Blog has a reference in each article that generally says something like: Updated: April 1, 1999 | Published: April 1, 1999 | Created: April 1, 1999 I have my model set up to allow manual...

IEnumerable Ajax.Beginform to Controller is null

model,controller,null,ajax.beginform
I have a view contains a list of users that is passed through the model. What I want to do is have a button for each user using which passes the userId back to the controller so that I could store it. Similar to a Like/Unlike Button. @model IEnumerable<FindaRoom.Models.FilterViewModel> <h3>List...

How can I add a field in a form from another distinct model in django?

django,forms,model
I have a form which is based in a model X which has some attribute fields, and I want to add a field, which is not from that model (the field is from another distinct model, in fact), in the same form. How can I add it?

Show the user “buy now” or “edit gig” or “download button” in Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller,model
This is the code i currently have <% if user_signed_in? && @gig.user == current_user %> <%= link_to "Edit your gig", edit_gig_path %> <% else %> <%= link_to "Get this gig for [email protected]} points", download_path(@gig)%> <% end %> The first line says if the user is singed in and the gig...

Loopback - GET model using custom String ID from MongoDB

database,mongodb,model,loopbackjs
I'm developing an API with loopback, everything worked fine until I decided to change the ids of my documents in the database. Now I don't want them to be auto generated. Now that I'm setting the Id myself. I get an "Unknown id" 404, whenever I hit this endpoint: GET...

Rails category (or filter) links in same controller?

ruby-on-rails,ruby,hyperlink,model,controller
Having trouble understanding how using links_to filter content within the same controller in the rails view works. My code is below: # index.html.erb (link nav area) <nav> <%= link_to 'Daily Monitoring', root_path(:category => "dailymonitoring") %> <%= link_to 'Smoke Tests', root_path(:category => "smoketests") %> </nav> # index.html.erb (cont.) <ul id="results"> <%...

Where do I put model so that whenever could access them?

ruby-on-rails,model,whenever
Simple and maybe stupid question. Just where? Simple generated model in /models doesn't work, and new class in /lib doesn't also... Just errors about undefined methods etc. schedule.rb every '* * * * *' do runner 'UpdateDaysAgo.test' end model class UpdateDaysAgo < ActiveRecord::Base def test UpdateDaysAgo.create(channel: "nil", title: "nil", game:...

How to check if any of the fields of a model are null or empty?

php,sql,yii,model
I have a model, $userModel. I want to check if any of the fields for this model are empty or null. At the moment I am doing it with a big if statement. if(!empty($userModel->name) && !empty($userModel->address) ... && !empty($userModel->email)) { // All fields have values } This way works, but...

Rails 4.1 ActiveRecord - Using Associated Model Properties in Query

ruby-on-rails,ruby,postgresql,activerecord,model
I'm building a search in my app, and I have three models: Company, Car, and Owner class Company < ActiveRecord::Base has_many :cars end class Car < ActiveRecord::Base belongs_to :company has_many :owners end class Owner < ActiveRecord::Base belongs_to :car end Each model has a name field. I'm trying to write an...

Django OneToOneField or ForeignKey?

django,django-models,model
My models.py: class User: // fields ... class Post: // fields ... class Comment: news = models.ForeignKey(Post) user = models.???(User) Each Post can have any number of Comments. But for each Post, I want a user to have only one Comment. How do I model this? I cannot do user...

ASP.NET MVC Client side time convert from model

javascript,asp.net-mvc,model
My cshtml page contains the following code for DateTime, which is some server time fetched from sql. <tbody> @{ foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.someDate) </td> The type of the someDate property is DateTime. I would like to show the time in respect to client/browser...

codeigniter filter database

codeigniter,filter,model,conditionals
i have a few checkboxes that filter my elements from a database but i don't know how to apply a filter like price with a min value and a max value, since from my view i can pass to the controller only one value of my inputs For example: i...

undefined local variable or method `n_days' when calling case variable in model method

ruby-on-rails,ruby,methods,model
In my habit model I created a new method: def current_level_days current_level[n_days] end How can we call the case variable of n_days in the new method so that I can achieve my larger goal of Counting the Days from the current_level? habit.rb class Habit < ActiveRecord::Base belongs_to :user has_many :comments,...

How to persist null value from server? (Groovy and JavaScript)

javascript,groovy,model,null
I'm returning an object (cmd) in the model from my Groovy controller. However, in the JavaScript in the GSP, it's converting null values to empty strings. For instance, <script> name:'${cmd.name.encodeAsHTML()}' </script> Omitting the quotes around the interpolation piece throws an error. How can I force the null value from the...

Rails rule of thumb: When to put things in 2 separate models/tables?

ruby-on-rails,ruby,database-design,model
When would you put data in multiple tables and when do you keep them in one and the same table? For example, what are the advantages and disadvantages of putting a system admin – who has exactly the same fields as another user type, except an additional Boolean for admin...

Call model method from different view

ruby-on-rails,ruby,methods,model
I have a model method def full_name_find(user_id) user = User.find(user_id) "#{user.first_name} #{user.last_name}" end that is in the User model. I would like to call it from another view (tickets#show) and I can't seem to get it to work. I tried: <%= User.full_name_find(comment.user_id) %> where comment has a user_id. I get...

NullReference Error while assiging values of Modeltype in MVC View (Razor)

vb.net,razor,model-view-controller,model
I have the following MVC Model: Public Class Employee Public Property EmployeeID As Integer End Class Controller: Namespace Controllers Public Class EmployeeController Inherits Controller Function Details() As ActionResult Dim employee As Employee employee = New Employee employee.EmployeeID = 101 Return View() End Function End Class End Namespace View: @ModelType MVCDemo.Employee...

Getting error when validating picture presence Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller,model
This is my Gig model class Gig < ActiveRecord::Base has_attached_file :image, :styles => { :medium => "360x170>", :bigger => "650x459>" } validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ validate :image_size_validation def image_size_validation if image.size > 2.megabytes errors.add(:base, "Image should be less than 2MB") end end end Everything works great,i can not upload...

Add field for an has_many association with :through

sql,ruby-on-rails,model,has-many-through,has-many
I have a question about has_many associations : Here is a sample of my db/models : Table document id : int name : text class Document < ActiveRecord::Base has_many :document_pages has_many :pages, through: :document_pages end Table page id : int content : text class Page < ActiveRecord::Base has_many :document_pages has_many...

Subclass of Django Model Not Accessible from Superclass

python,django,inheritance,model
I'm trying to create an inherited model in Django like that below. I should be able to call, for an instance superclass = Superclass(), I should be able to call superclass.subclass, and access the requisite fields. When I do that, I'm told that '1 argument was expected, and 8 were...

Odoo Prefilter many2one / many2many / one2many

orm,model,odoo
How can I predefinde/prefilter a many2one field? As example product.category has a type, in my view the user should only be able to select a product.category based on the category type. //field in model category_id = fields.Many2one(comodel_name="product.category", string="ebay Category", required=True) //field in view How can I prefilter the select in...

Qt Model and View - Link data from model to view, how?

qt,view,model,signals,slots
I'm pretty new to the Model and View concept and I'm having trouble finding the right way to do this. So in my understanding the concept means, that I have one class that handles all the view (GUI) parts and an other class which handles the data processing. The GUI...

Distribute entity framework models over different assemblies

c#,.net,entity-framework,model,entity-framework-6
Currently i am trying to use entity framework 6.3 with a kind of distributed models. My problem is, i want to seperate the models in different assemblies (for example the core application and plugins). Now i'm search for a way, that my application get all models over reflection or some...

How to find the total number of downloads a gig had in Rails 4?

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller,model
This is the models relationship i have For Purchase.rb class Purchase < ActiveRecord::Base belongs_to :gig belongs_to :buyer, class_name: 'User' belongs_to :seller, class_name: 'User' end For User.rb class User < ActiveRecord::Base has_many :purchases, foreign_key: 'buyer_id' has_many :gigs, through: :purchases, source: :buyer has_many :gigs has_many :sales, foreign_key: 'seller_id', class_name: 'Purchase' end For...

Rails 4: Complex Many to Many Relationships

ruby-on-rails,activerecord,database-design,model,associations
I have the following models.. Provider Patient Clinic Like an eco-system, all models should have many-to-many relationships with one another. It's very important that I am able to query data from all directions. After intensive research on Active Record associations, I find many blogs warning against has_and_belongs_to_many and using has_many...

ExtJS - convert json to Model

json,extjs,model
I have a json string that I need to map into a Model, I've been checking this json reader, Ext.data.reader.JsonView, but it seems that it only wokrs with a proxy, I need to pass a string (which contains the json) and map it to my model. Is that possible? Thanks,...

Rails 4 Attendance system

ruby-on-rails,ruby,ruby-on-rails-4,model
Hi I'm actually struggling with building a Rails 4 application implementing an attendance model on rails 4, I found maybe two question on stackoverflow but they're posted in 2012 and it failed when i tried following them. This is the closest one i got on stackoverflow Edit: I already have...

Ruby error while migrating database and seed

ruby-on-rails,ruby,model
http://pastebin.com/a8fVSCcA I am trying to implement a Questions and answers model, I've added a has_many and a belongs_to but they seem to be causing errors. [email protected]:~/workspace (master) $ rake db:migrate == 20150509125146 CreateQuestions: migrating ================================== -- create_table(:questions) -- has_many(:answers) rake aborted! StandardError: An error has occurred, this and all later...

Custom .find() tied to a Sequelize Model

model,find,sequelize.js
Couldn't find what I wanted in the documentation, so I'm just going to leave this here and hope for some help! I have a specific query that I need to run on my user Model with a lot of includes and those includes all have where statements inside of them......

How to create 3d model to display for online use

html,model,minecraft
So this question may seem hard to understand and very vague and that's because I have no other way of explaining this, so I'll try and describe what I want to achieve. So essentially I want to create a character model (based from the protagonist of Minecraft, Steve). What I'd...

Direct X 11 Problems

parsing,model,loading,directx-11,.obj
So I am making a game engine in DX11 and this is a strange problem I have been having for a while. http://gfycat.com/MerryLikableGreyhounddog I thought it was the back facing normals but that doesn't make a difference. I tried the culling modes. No luck The thing to look at in...

Points exchange between users Rails 4

ruby-on-rails,ruby,database,model-view-controller,model
this is the main idea of my website The user number 1 see a picture he likes(uploaded by user number 2) if user number 1 has enough points(the specific number selected by user number 2) he clicks on download link,and gets redirected to the download page...and the user number 2...

Rails nested variables without more models

ruby-on-rails,model,nested
I'm using Rails 4 and have a Policy model. This model has a ton of attributes that I would like to organize in sub-groups of sorts. This is an example: A policy has base information such as name, address, type. Is there a way to organize the model such that...

model isn't working as expected C#

c#,model,mapping,dapper
My model is getting data I need, but I'm not sure how to organize it in the way I need. I have it where the model pulls a team, and a player. The issue is when mapping my data to the model it gives me duplicate teams, and doesn't allow...

Change model before Form Submit in MVC

c#,asp.net-mvc,model,form-submit
I have created the following form: @using (Html.BeginForm("Export", "ExportDefinitions", FormMethod.Post, new { ExportModel = Model })) { <input name="button" type="submit" value="Export" /> } Above this form is a object, allowing multiple ID's to be selected. This needs to be submitted as well. The C# "ExportDefinitions" defines are: public string SelectedIds...

How to count a method within a method

ruby-on-rails,ruby,methods,model,integer
If we create a new method called days_left_in_current_level, what would we need to put in there so that we can count how many days are left in the current_level? habit.rb def current_level return 0 unless date_started def committed_wdays committed.map do |day| Date::ABBR_DAYNAMES.index(day.titleize) end end def n_days ((date_started.to_date)..Date.today).count do |date| committed_wdays.include?...

Querying a Pivot table in Laravel 4

mysql,laravel,laravel-4,model,relationship
I have a Email model with the table 'messages' that contains all the message data. I also have a pivot table 'message_users'. How could I return all the messages that a user is associated with? ...

Rails scope multiple attributes in model

ruby-on-rails,ruby,ruby-on-rails-4,model,scope
I’m trying to set up a scope on my Job model to show me records that match the following: survey_date is in the past. survey_file has a value. quote_file has no value. How might I edit the following to make this scope work? scope :awaiting_quote, lambda { where('survey_date < ?...

How to make a def inherit from another def,from the same controller Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller,model
This is what i have in my gig controller def downloadpage ActiveRecord::Base.transaction do if current_user.points >= @gig.pointsneeded current_user.points -= @gig.pointsneeded @gig.user.points += @gig.pointsneeded current_user.save @gig.user.save redirect_to @gig.boxlink else redirect_to :back, notice: "You don't have enough points" end end end def success_download end The def downloadpage ,makes the points exchange between...

Rails - Create and update two models in one controller - SOLVED

ruby-on-rails,model,controller
I would like to create a model and update one part of an other at the same time. I have two models Order and Listing. Order belongs_to :listing and Listing has_many :orders When a user fills up the order form, an order is created. In the URL there is a...

Django, multi-table inheritance is that bad?

django,database-design,model
This isn't really specific to django. One can model Place (with location, name, and other common attributes) - Restaurant (menu..) - ConcertHall (hall size..) in two separate tables and let each one hold all the fields they need. (in django world, this is called abstract inheritance) in three tables, where...

Database/Code solutions for model with dynamic data, using Symfony 2 with Doctrine

database,symfony2,model,doctrine,nosql
I'm making an application with Symfony2 and Doctrine and i'm facing a problem i've always wondered about but it's never been an issue until today: How to handle dynamic data? In the application i'm developing there will be some data that might be relational and to which a relational database...

Update model with $http using a service not triggering model change

angularjs,http,model,angularjs-service
I have the following model: var MODEL = { myTable: [], anotherTable: [] }; //--- initially set as empty arrays MODEL is a global variable as it is used to bind the app model in different controllers. I have devined a service that updates the model, getting the data from...

Visual Studio.net MVC: The model on a view is null

linq,entity-framework,model-view-controller,model
I am using RedirectToAction to load a new page after login and pass in the database model with it. RedirectToAction("AdministrationPortal", "Manage", person); person.user model is a User class created by the entity framework. The model of person is class Person { public User user { get; set; }; public string...

how to allow text attributes to be empty in Yii model?

validation,yii,model
I have a model for articles, the article can be written in two languages, English and Arabic. So there are 2 attributes for each language text, I want the both attributes to be allowed to be empty on create and update, knowing that the attributes type are text not varchar....

Django UserAdmin customization

django,model,admin
Within my Users page, I would like to add more column fields to display for each user. By default, the User page shows username, first name, last name, email, and staff status, but I would also like to add the column "Chosen Groups" to be displayed as well. Each user...

Laravel Collection of models in one edit form

php,forms,laravel,model,laravel-5
i have a little question on laravel Forms, supposing that i have a 1:n relation, like one post can have many comments, and many comments are for one post only. I want to have an single edit page for all the comments of one post. I have in [email protected] :...

Linking a user id to a profile model - Ruby on Rails

ruby-on-rails,ruby,model,devise,scaffolding
I have a basic rails app with devise set up and a profile model generated with scaffolding. The Profile model is where the user will add detailed information about themselves after they sign up. Everything is working fine except for one issue: after the user creates a profile, the new...

In Firefox, Angular model doesn't update until focus leaves dropdown. How to properly set focus when tabbing?

angularjs,firefox,drop-down-menu,model,accessibility
I have a select element. The selected value determines whether a text input box shows up afterwards (using ng-show). For accessibility purposes, I want the user to be able to tab seamlessly through the inputs; as soon as they tab away from the select, I want the new input box...

Url.Content returns null when it has value

asp.net-mvc,model
I have an interesting error which I couldn't debug and find information online. Got a screenshot of the error. Please see... This is the details view of my controller. There are many records in that database table and some of them returns that error when I click the records on...

How to specify file type for a variable, in the model file?

ruby-on-rails,ruby,xml,ruby-on-rails-4,model
In one of my model files I would like to specify for a variable (called xml_file) that it should be an xml file. What I've tried so far generated error messages. Attempt 1 validates :xml_file, presence: true, content_type: %w(application/xml) On rake test this generated the error ArgumentError: Unknown validator: 'ContentTypeValidator'....

How to self join a many to many table in cakephp 3?

model,many-to-many,cakephp-3.0,self-join
I try to self join my table user to get parent-child associations but it didn't work here is my association in the Users model: $this->belongsToMany('Parents', [ 'className' => 'Users', 'joinTable' => 'users_users', 'foreignKey' => 'id', 'targetForeignKey' => 'parent_id' ]); $this->belongsToMany('Childs', [ 'className' => 'Users', 'joinTable' => 'users_users', 'foreignKey' => 'id',...

Link a button to a python function from my model (Odoo 8)

python,model,odoo,odoo-8
I get trouble linking a button to a function (python) from my model. I searched on the net but got only few informations for Odoo 8. That is my code right now: My function from my model (mymodule.service): def main_val(self, context=None): if context is None: context = {} [...] The...

Django - Feeding only part of Foreignkey in models

django,forms,filter,model,foreign-keys
i'm new to django and as a exercise I want to make "home expenses". I've already did simple model and form : (from models) #models.py #these are the type (groceries/clothes/etc. ) class TypWydatku(models.Model): typ_wydatku = models.CharField(max_length=25) data_wpisu=models.DateField(auto_now_add=True) #these are the actual input with dates/prices/etc class Wpisy(models.Model): data_zakupu=models.DateField(default=timezone.now()) data_wpisu=models.DateField(auto_now=True) typ_wydatku=models.ForeignKey(TypWydatku)...

Cannot access associated model attributes within a form

ruby-on-rails,ruby,forms,model,has-many-through
I am trying to build a form for a has_many :through relationship. The Problem is, that I can access the attributes from the join table (:through) in the form, but not the other table. My models look like this: class Recipe < ActiveRecord::Base has_many :quantities has_many :ingredients, through: :quantities accepts_nested_attributes_for...

Using dropdownlistfor for model with list property

c#,asp.net-mvc,asp.net-mvc-4,model
How do I use dropdownlistfor for this viewmodel? public class ViewModel { public IEnumerable<Model1> model1{ get; set; } } public class Model1 { public string Name { get; set; } public int Id{ get; set; } } How should I do this? @model Models.ViewModels.ViewModel @Html.DropDownListFor(model => model.model1) ...

mongodb populate method not working

node.js,mongodb,model,populate,auto-populate
Here is my code for models var postSchema = new mongoose.Schema({ created_by: {type: Schema.ObjectId, ref:'User', autopopulate: true }, //should be changed to ObjectId, ref "User" created_at: {type: Date, default: Date.now}, text: String }); var userSchema = new mongoose.Schema({ username: String, password: String, //hash created from password created_at: {type: Date, default:...

Custom accessors Eloquent Model

arrays,laravel,model,eloquent
I have a Eloquent Model and I want to create a customized toArray method... class Posts extends Model { public function scopeActives($query) { return $query->where('status', '=', '1'); } public function toCustomJS() { $array = parent::ToArray(); $array['location'] = someFunction($this->attributes->location); return $array; } } //In my controller: Posts::actives()->get()->toArray(); //this is working Posts::actives()->get()->toCustomJS();...