Search Results

Search found 296 results on 12 pages for 'validations'.

Page 9/12 | < Previous Page | 5 6 7 8 9 10 11 12  | Next Page >

  • JQuery Validate: only takes the last addMethod?

    - by Neuquino
    Hi, I need to add multiple custom validations to one form. I have 2 definitions of addMethod. But it only takes the last one... here is the code. $(document).ready(function() { $.validator.addMethod("badSelectionB",function(){ var comboValues = []; for(var i=0;i<6;i++){ var id="comision_B_"+(i+1); var comboValue=document.getElementById(id).value; if($.inArray(comboValue,comboValues) == -1){ comboValues.push(comboValue); }else{ return false; } } return true; },"Seleccione una única prioridad por comisión."); $.validator.addMethod("badSelectionA",function(){ var comboValues = []; for(var i=0;i<6;i++){ var id="comision_A_"+(i+1); var comboValue=document.getElementById(id).value; if($.inArray(comboValue,comboValues) == -1){ comboValues.push(comboValue); }else{ return false; } } return true; },"Seleccione una única prioridad por comisión."); $("#inscripcionForm").validate( { rules : { nombre : "required", apellido : "required", dni : { required: true, digits: true, }, mail : { required : true, email : true, }, comision_A_6: { badSelectionA:true, }, comision_B_6: { badSelectionB: true, } }, messages : { nombre : "Ingrese su nombre.", apellido : "Ingrese su apellido.", dni : { required: "Ingrese su dni.", digits: "Ingrese solo números.", }, mail : { required : "Ingrese su correo electrónico.", email: "El correo electrónico ingresado no es válido." } }, }); }); Do you have any clue of what is happening? Thanks in advance,

    Read the article

  • Get paperclip to crop the image without validating

    - by Micke
    Hello fellow stackoverflow members. I have been following this guide to enable users to have their own avatar. But i have bumped in to a litle problem. When the user is cropping the image the model tries to validate all my validations. My user model looks like this: class User < ActiveRecord::Base has_attached_file :avatar, :styles => { :small => "100x100>", :large => "500x500>" }, :processors => [:cropper] attr_accessor :password, :crop_x, :crop_y, :crop_w, :crop_h attr_accessible :crop_x, :crop_y, :crop_w, :crop_h validates_confirmation_of :password validates_presence_of :password And when the user runs the crop updating script the user model tries to validate the password. But because i have no password field on the cropping page it can't validate it. Here is the updating of the crop: @user = User.find(current_user.id) if @user.update_attributes(params[:user]) flash[:notice] = "Successfully updated user." end How can i bypass this in a easy and clean way?

    Read the article

  • How do you keep your business rules DRY?

    - by Mario
    I periodically ponder how to best design an application whose every business rule exists in just a single location. (While I know there is no proverbial “best way” and that designs are situational, people must have a leaning toward one practice or another.) I work for a shop where they prefer to house as much of the business rules as possible in the database. This requires developers in many cases to perform identical front-end validations to avoid sending data to the database that will result in an exception—not very DRY. It grates me anytime I find myself duplicating any kind of logic—even lowly validation logic. I am a single-point-of-truth purist to an anal degree. On the other end of the spectrum, I know of shops that create dumb databases (the Rails community leans in this direction) and handle all of the business logic in a separate tier (in Rails the models would house “most” of this). Note the word “most” which implies that some business logic does end up spilling into other places (in Rails it might spill over into the controllers). In way, a clean separation of concerns where all business logic exists in a single core location is a Utopian fantasy that’s hard to uphold (n-tiered architecture or not). Furthermore, is see the “Database as a fortress” and would agree that it should be built on constraints that cause it to reject bad data. As such, I hold principles that cause a degree of angst as I attempt to balance them. How do you balance the database-as-a-fortress view with the desire to have a single-point-of-truth?

    Read the article

  • Rails: keeping DRY with ActiveRecord models that share similar complex attributes

    - by Greg
    This seems like it should have a straightforward answer, but after much time on Google and SO I can't find it. It might be a case of missing the right keywords. In my RoR application I have several models that share a specific kind of string attribute that has special validation and other functionality. The closest similar example I can think of is a string that represents a URL. This leads to a lot of duplication in the models (and even more duplication in the unit tests), but I'm not sure how to make it more DRY. I can think of several possible directions... create a plugin along the lines of the "validates_url_format_of" plugin, but that would only make the validations DRY give this special string its own model, but this seems like a very heavy solution create a ruby class for this special string, but how do I get ActiveRecord to associate this class with the model attribute that is a string in the db Number 3 seems the most reasonable, but I can't figure out how to extend ActiveRecord to handle anything other than the base data types. Any pointers? Finally, if there is a way to do this, where in the folder hierarchy would you put the new class that is not a model? Many thanks.

    Read the article

  • Strange error coming from ActiveRecord (probably)

    - by artemave
    My development environment: Ubuntu 9 Ruby 1.9.1/1.8.7 (rvm) Rails 2.3.5 Mysql 5.0 Apache Passenger Below is the part of the program flow to represent the issue. Request comes: #action def create begin @report = Report.new(params[:report]) ... rescue LocationNotFound => e ... end end Report constructor: class Report attr_accessor :locations def initialize(params = {}) @locations = params[:locations] ? fetch_locations(params[:locations]) : [] end ... end fetch_locations: def fetch_locations(loc_names) Rails.logger.debug "LOC_NAMES: " + loc_names.inspect ls = Location.find(:all, :conditions => [ # line 57 "locations.name in (#{loc_names.map{'?'}.join(',')})", *loc_names ], :include => [:sample_summaries, :samples]) # loc_names will never be empty ... end Location model: class Location < ActiveRecord::Base has_many :sample_summaries has_many :samples, :through => :sample_summaries ... end Now, the first time (after passenger restart) this runs fine and does the job. Most of the consequent times I get the error: Mar-11 11:01:00 #15098 DEBUG: LOC_NAMES: ["Moscow, RF", "London, UK"] Mar-11 11:01:00 #15098 DEBUG: Location Load (0.0ms) SELECT * FROM `locations` WHERE (locations.name in ('Moscow, RF','London, UK')) Mar-11 11:01:00 #15098 DEBUG: SampleSummary Load (0.0ms) SELECT `sample_summaries`.* FROM `sample_summaries` WHERE (`sample_summaries`.location_id IN (1,3)) Mar-11 11:01:00 #15098 DEBUG: SampleSummary Columns (0.0ms) SHOW FIELDS FROM `sample_summaries` Mar-11 11:01:00 #15098 FATAL: NoMethodError (You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.include?): app/models/report.rb:57:in `fetch_locations' app/models/report.rb:9:in `initialize' app/controllers/report_controller.rb:11:in `new' app/controllers/report_controller.rb:11:in `create' Looks quite random to me. Any ideas? P.S. I also tried to wrap the query in uncached block, but that didn't change anything. EDIT Here is what SampleSummary model looks like: class SampleSummary < ActiveRecord::Base has_many :samples belongs_to :location ... #validations default_scope :include => :samples, :order => 'rss_ts desc' ... end

    Read the article

  • Authlogic and password and password confirmation attributes - inaccessible?

    - by adam
    Im trying to test my successfully creates a new user after login (using authlogic). Ive added a couple of new fields to the user so just want to make sure that the user is saved properly. The problem is despite creating a valid user factory, whenever i try to grab its attributes to post to the create method, password and password confirmation are being ommitted. I presuem this is a security method that authlogic performs in the background. This results in validations failing and the test failing. Im wondering how do i get round this problem? I could just type the attributes out by hand but that doesnt seem very dry. context "on POST to :create" do context "on posting a valid user" do setup do @user = Factory.build(:user) post :create, :user => @user.attributes end should "be valid" do assert @user.valid? end should_redirect_to("users sentences index page") { sentences_path() } should "add user to the db" do assert User.find_by_username(@user.username) end end ##User factory Factory.define :user do |f| f.username {Factory.next(:username) } f.email { Factory.next(:email)} f.password_confirmation "password" f.password "password" f.native_language {|nl| nl.association(:language)} f.second_language {|nl| nl.association(:language)} end

    Read the article

  • One Model to Rule Them All - VS2010 UML, ADO.NET Entity Data Model, and T4

    - by Eric J.
    I worked on a fairly large project a while back where we modeled the classes in Enterprise Architect and generated the (partial) POCO classes (complete with model-driven business rule validations), persistence (NHibernate mapping file) and DDL. Based on certain model attributes we could flag alternate generation strategies or indicate that a particular portion would be entirely hand-coded. There was a good deal of initial investment, but it paid large dividends over the lifetime of a 15 developer, 3 year project. I'm investigating doing something similar with the current Microsoft technology stack. The place I'm stuck is that class modeling is done with the VS 2010 UML tools, but logical data modeling is done with Entity Data Modeler. Is it a reasonable path to use VS 2010 UML as the "single source of truth" and code generate the edmx files based on the class model? That's the inverse of the common path to create the entity model and use a POCO generator to generate classes. However, a good class model can be used to generate much more than just the properties so I tend to view it as a better choice than the entity model.

    Read the article

  • Nested forms and automatic creation of parent, children

    - by Karen
    Guys, I was wondering if it was possible to create new parent, children in a has many relationship, using rails nested forms. Rails documentation clearly says that this works in a one to one relationship. Not sure if its the same in has many relationship. For example: If params = { :employee => { :name => "Tester", :account_attributes => {:login => 'tester'} } } works as one to one relationship. So Employee.new(params) works fine. New employee, account are created. Supposing I had params = { :employee => { :name => "Tester", :account_attributes => { "0" => {:login => 'tester'}, "1" => {:login => 'tester2'} } } } Employee.new(params) doesnt work. It fails on child validations saying parent cant be blank. Any help is appreciated. Thanks Karen

    Read the article

  • ASP.NET: aggregating validators in a user control

    - by orsogufo
    I am developing a web application where I would like to perform a set of validations on a certain field (an account name in the specific case). I need to check that the value is not empty, matches a certain pattern and is not already used. I tried to create a UserControl that aggregates a RequiredFieldValidator, a RegexValidator and a CustomValidator, then I created a ControlToValidate property like this: public partial class AccountNameValidator : System.Web.UI.UserControl { public string ControlToValidate { get { return ViewState["ControlToValidate"] as string; } set { ViewState["ControlToValidate"] = value; AccountNameRequiredFieldValidator.ControlToValidate = value; AccountNameRegexValidator.ControlToValidate = value; AccountNameUniqueValidator.ControlToValidate = value; } } } However, if I insert the control on a page and set ControlToValidate to some control ID, when the page loads I get an error that says Unable to find control id 'AccountName' referenced by the 'ControlToValidate' property of 'AccountNameRequiredFieldValidator', which makes me think that the controls inside my UserControl cannot resolve correctly the controls in the parent page. So, I have two questions: 1) Is it possible to have validator controls inside a UserControl validate a control in the parent page? 2) Is it correct and good practice to "aggregate" multiple validator controls in a UserControl? If not, what is the standard way to proceed?

    Read the article

  • when does factory girl create objects in db?

    - by Pavel K.
    i am trying to simulate a session using factory girl/shoulda (it worked with fixtures but i am having problems with using factories). i have following factories (user login and email both have 'unique' validations): Factory.define :user do |u| u.login 'quentin' u.email '[email protected]' end Factory.define :session_user, :class => Session do |u| u.association :user, :factory => :user u.session_id 'session_user' end and here's the test class MessagesControllerTest < ActionController::TestCase context "normal user" do setup do @request.session[:user_id]=Factory(:user).id @request.session[:session_id]=Factory(:session_user).session_id end should "be able to access new message creation" do get :new assert_response :success end end end but when i run "rake test:functionals", i get this test result 1) Error: test: normal user should be able to access new message creation. (MessagesControllerTest): ActiveRecord::RecordInvalid: Validation failed: Account name already exists!, Email already exists! which means that record already exists in db when i am referring to it in test setup. is there something i don't understand here? does factory girl create all factories in db on startup? rails 2.3.5/shoulda/factory girl

    Read the article

  • How to get interpolated message in NHibernate.Validator

    - by SztupY
    Hi! I'm trying to integrate NHibernate.Validator with ASP.NET MVC client side validations, and the only problem I found is that I simply can't convert the non-interpolated message to a human-readable one. I thought this would be an easy task, but turned out to be the hardest part of the client-side validation. The main problem is that because it's not server-side, I actually only need the validation attributes that are being used, and I don't actually have an instance or anything else at hand. Here are some excerpts from what I've been already trying: // Get the the default Message Interpolator from the Engine IMessageInterpolator interp = _engine.Interpolator; if (interp == null) { // It is null?? Oh, try to create a new one interp = new NHibernate.Validator.Interpolator.DefaultMessageInterpolator(); } // We need an instance of the object that needs to be validated, se we have to create one object instance = Activator.CreateInstance(Metadata.ContainerType); // we enumerate all attributes of the property. For example we have found a PatternAttribute var a = attr as PatternAttribute; // it seems that the default message interpolator doesn't work, unless initialized if (interp is NHibernate.Validator.Interpolator.DefaultMessageInterpolator) { (interp as NHibernate.Validator.Interpolator.DefaultMessageInterpolator).Initialize(a); } // but even after it is initialized the following will throw a NullReferenceException, although all of the parameters are specified, and they are not null (except for the properties of the instance, which are all null, but this can't be changed) var message = interp.Interpolate(new InterpolationInfo(Metadata.ContainerType, instance, PropertyName, a, interp, a.Message)); I know that the above is a fairly complex code for a seemingly simple question, but I'm still stuck without solution. Is there any way to get the interpolated string out of NHValidator?

    Read the article

  • Rails form protection questions, hidden field

    - by user284194
    I have a live rails website and I want to have a form with a lot of fields on it. I have set up validations and allowed formatting for every field. I've tested it quite a bit and it seems to catch anything I throw at it. I think it's almost ready to go live, but I want to quadruple check if there's anything else I should do to protect it. My site has a low volume of visitors, but I want it to be a safe as possible. I'd like to avoid using a captcha if I can. I've read that you can use a hidden field to protect forms against bots. Do people recommend this instead of using a captcha, or even using it with a captcha? my form is really standard: <% form_for(@entry) do |f| %> ... <%= f.submit 'Create' %> <% end %> Any suggestions or code samples would be greatly appreciated.

    Read the article

  • Multiple user roles in Ruby on Rails

    - by aguynamedloren
    I am building an inventory management application with four different user types: admin, employee, manufacturer, transporter. I haven't started coding yet, but this is what I'm thinking.. Manufacturers and transporters are related with has_many :through many-to-many association with products as follows: class Manufacturer < ActiveRecord::Base has_many :products has_many :transporters, :through => :products end class Product < ActiveRecord::Base belongs_to :manufacturer belongs_to :transporter end class Transporter < ActiveRecord::Base has_many :products has_many :manufacturers, :through => :products end All four user types will be able to login, but they will have different permissions and views, etc. I don't think I can put them in the same table (Users), however, because they will have different requirements, ie: vendors and manufacturers must have a billing address and contact info (through validations), but admins and employees should not have these fields. If possible, I would like to have a single login screen as opposed to 4 different screens. I'm not asking for the exact code to build this, but I'm having trouble determining the best way to make it happen. Any ideas would be greatly appreciated - thanks!

    Read the article

  • Shoulda and Paperclip testing

    - by trobrock
    I am trying to test a couple models that have an attachment with Paperclip. I have all of my validations passing except for the content-type check. # myapp/test/unit/project_test.rb should_have_attached_file :logo should_validate_attachment_presence :logo should validate_attachment_size(:logo).less_than(1.megabyte) should_validate_attachment_content_type :logo, :valid => ["image/png", "image/jpeg", "image/pjpeg", "image/x-png"] # myapp/app/models/project.rb has_attached_file :logo, :styles => { :small => "100x100>", :medium => "200x200>" } validates_attachment_presence :logo validates_attachment_size :logo, :less_than => 1.megabyte validates_attachment_content_type :logo, :content_type => ["image/png", "image/jpeg", "image/pjpeg", "image/x-png"] The errors I am getting: 1) Failure: test: Client should validate the content types allowed on attachment logo. (ClientTest) [/Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/assertions.rb:55:in `assert_accepts' vendor/plugins/paperclip/shoulda_macros/paperclip.rb:44:in `__bind_1276100387_499280' /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `call' /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `test: Client should validate the content types allowed on attachment logo. ']: Content types image/png, image/jpeg, image/pjpeg, image/x-png should be accepted and rejected by logo This happens on two different models that are set up the same way.

    Read the article

  • Ignoring a model with all blank fields in Ruby on Rails

    - by aguynamedloren
    I am trying to create multiple items (each with a name value and a content value) in a single form. The code I have is functioning, but I cannot figure out how to ignore items that are blank. Here's the code: #item.rb class Item < ActiveRecord::Base attr_accessible :name, :content validates_presence_of :name, :content end #items_controller.rb class ItemsController < ApplicationController def new @items = Array.new(3){ Item.new } end def create @items = params[:items].values.collect{|item|Item.new(item)} if @items.each(&:save!) flash[:notice] = "Successfully created item." redirect_to root_url else render :action => 'new' end end #new.html.erb <% form_tag :action => 'create' do %> <%@items.each_with_index do |item, index| %> <% fields_for "items[#{index}]", item do |f| %> <p> Name: <%= f.text_field :name %> Content: <%= f.text_field :content %> </p> <% end %> <% end %> <%= submit_tag %> <% end %> This code works when all fields for all items are filled out in the form, but fails if any fields are left blank (due to validations). The goal is that 1 or 2 items could be saved, even if others are left blank. I'm sure there is a simple solution to this, but I've been tinkering for hours with no avail. Any help is appreciated!

    Read the article

  • Which Code Should Go Where in MVC Structure

    - by Oguz
    My problem is in somewhere between model and controller.Everything works perfect for me when I use MVC just for crud (create, read, update, delete).I have separate models for each database table .I access these models from controller , to crud them . For example , in contacts application,I have actions (create, read, update, delete) in controller(contact) to use model's (contact) methods (create, read, update, delete). The problem starts when I try to do something more complicated. There are some complex processes which I do not know where should I put them. For example , in registering user process. I can not just finish this process in user model because , I have to use other models too (sending mails , creating other records for user via other models) and do lots of complex validations via other models. For example , in some complex searching processes , I have to access lots of models (articles, videos, images etc.) Or, sometimes , I have to use apis to decide what I will do next or which database model I will use to record data So where is the place to do this complicated processes. I do not want to do them in controllers , Because sometimes I should use these processes in other controllers too. And I do not want to put these process in models because , I use models as database access layers .May be I am wrong,I want to know . Thank you for your answer .

    Read the article

  • Have error message show when form is created through AJAX

    - by Railslearner
    I have a page called /add that you can add a Dog on and the form is in its own partial. I'm using Simple Form and Twitter Bootstrap. I added the files for the main Bootstrap but use a gem for simple_form to work with it just so you know. DogsController # new.js.erb (deleted new.html.erb) def new @dog = Dog.new respond_to do |format| format.js end end # create.js.erb def create @dog = current_user.dogs.new(params[:dog]) respond_to do |format| if @dog.save format.html { redirect_to add_url, notice: 'Dog was successfully added.' } format.json { render json: @dog, status: :created, location: @dog} format.js else format.html { render 'pages/add' } format.json { render json: @dog.errors, status: :unprocessable_entity } end end end dogs/_form.html.erb <%= simple_form_for(@dog, :remote => true) do |f| %> <%= render :partial => "shared/error_message", :locals => { :f => f } %> <%= f.input :name %> <%= f.button :submit, 'Done' %> <% end %> This line: <%= render :partial => "shared/error_message", :locals => { :f => f } %> Is for bootstrap so it renders the errors html correctly. PagesController def add respond_to do |format| format.html end end pages/add.html.erb <div id="generate-form"> </div> dogs/new.js.erb $("#generate-form").html("<%= escape_javascript(render(:partial => 'dogs/form', locals: { dog: @dog })) %>"); Now how would I get this to render the error partial as if it was still on my dogs/new.html.erb since its being created through AJAX? I don't need client side validations do I?

    Read the article

  • password validator using RegExp in Flex

    - by kalyaniRavi
    I have seen several examples in Flex for passowrd validator using RegExp. But every where the validation is happend for single validation. I have a requirement, like password validations like • At least one Upper case letter • At least one numeric character • At least one special character such as @, #, $, etc. • At least one Lower case letter • password lenght minimum 6 digits • password cannot be same as user name Can anyone provide me a code for this..? I have the code only for checking the password is valid or not . check the below code. MXML CODE <mx:FormItem label="Username:" x="83" y="96" width="66"> </mx:FormItem> <mx:FormItem label="Password:" x="88" y="123" width="61"> </mx:FormItem> <mx:Button label="Login" id="btnLogin" tabIndex="2" click="login();" enabled="{formIsValid}" x="327" y="162" width="84"/> <mx:TextInput id="txtPassword" displayAsPassword="true" change="validateForm(event);" x="152" y="121" width="217"/> <mx:TextInput id="txtUserId" change="validateForm(event);" x="152" y="94" width="217"/> AS Code: private function validateForm(event:Event):void { focussedFormControl = event.target as DisplayObject; formIsValid = true; formIsEmpty = (txtUserId.text == "" && txtPassword.text == ""); validate(strVUserId); validate(strVPassword); } private function validate(validator:Validator):Boolean { var validatorSource:DisplayObject = validator.source as DisplayObject; var suppressEvents:Boolean = (validatorSource != focussedFormControl); var event:ValidationResultEvent = validator.validate(null, suppressEvents); var currentControlIsValid:Boolean = (event.type == ValidationResultEvent.VALID); formIsValid = formIsValid && currentControlIsValid; return currentControlIsValid; }

    Read the article

  • N-tier architecture and unit tests (using Java)

    - by Alexandre FILLATRE
    Hi there, I'd like to have your expert explanations about an architectural question. Imagine a Spring MVC webapp, with validation API (JSR 303). So for a request, I have a controller that handles the request, then passes it to the service layer, which passes to the DAO one. Here's my question. At which layer should the validation occur, and how ? My though is that the controller has to handle basic validation (are mandatory fields empty ? Is the field length ok ? etc.). Then the service layer can do some tricker stuff, that involve other objets. The DAO does no validation at all. BUT, if I want to implement some unit testing (i.e. test layers below service, not the controllers), I'll end up with unexpected behavior because some validations should have been done in the Controller layer. As we don't use it for unit testing, there is a problem. What is the best way to deal with this ? I know there is no universal answer, but your personal experience is very welcomed. Thanks a lot. Regards.

    Read the article

  • JQuery Validate: only takes the first addMethod?

    - by Neuquino
    Hi, I need to add multiple custom validations to one form. I have 2 definitions of addMethod. But it only takes the first one... here is the code. $(document).ready(function() { $.validator.addMethod("badSelectionB",function(){ var comboValues = []; for(var i=0;i<6;i++){ var id="comision_B_"+(i+1); var comboValue=document.getElementById(id).value; if($.inArray(comboValue,comboValues) != 0){ comboValues.push(comboValue); }else{ return false; } } return true; },"Seleccione una única prioridad por comisión."); $.validator.addMethod("badSelectionA",function(){ var comboValues = []; for(var i=0;i<6;i++){ var id="comision_A_"+(i+1); var comboValue=document.getElementById(id).value; if($.inArray(comboValue,comboValues) != 0){ comboValues.push(comboValue); }else{ return false; } } return true; },"Seleccione una única prioridad por comisión."); $("#inscripcionForm").validate( { rules : { nombre : "required", apellido : "required", dni : { required: true, digits: true, }, mail : { required : true, email : true, }, comision_A_6: { badSelectionA:true, }, comision_B_6: { badSelectionB: true, } }, messages : { nombre : "Ingrese su nombre.", apellido : "Ingrese su apellido.", dni : { required: "Ingrese su dni.", digits: "Ingrese solo números.", }, mail : { required : "Ingrese su correo electrónico.", email: "El correo electrónico ingresado no es válido." } }, }); }); Do you have any clue of what is happening? Thanks in advance,

    Read the article

  • How do I model teams and gameplay in this scorekeeping application?

    - by Eric Hill
    I'm writing a scorekeeping application for card game that has a few possibly-interesting constraints. The application accepts user registrations for players, then lets them check-in to a particular game (modeled as Event). After the final player registers, the app should generate teams, singles or doubles, depending on the preference of the person running the game and some validations (can't do doubles if there's an odd number checked in). There are @event.teams.count rounds in the game. To sum up: An event consists of `@event.teams.count` rounds; Teams can have 1 or more players Events have n or n/2 teams (depending on whether it's singles or doubles) Users will be members of different teams at different events Currently I have a rat's nest of associations: class User < ActiveRecord::Base has_many :teams, :through => :players has_many :events, :through => :teams class Event < ActiveRecord::Base has_many :rounds has_many :teams has_many :players, :through => :teams class Player < ActiveRecord::Base belongs_to :user belongs_to :team end class Team < ActiveRecord::Base has_many :players belongs_to :event end class Round < ActiveRecord::Base belongs_to :event belongs_to :user end The sticky part is team generation. I have basically a "start game" button that should freeze the registrations and pair up teams either singly or doubly, and render to Round#new so that the first (and subsequent) matches can be scored. Currently I'm implementing this as a check on Round#new that calls Event#generate_teams and displays the view: # Event#generate_teams def generate_teams # User has_many :events, :through => :registrations # self.doubles is a boolean denoting 2 players per team registrations.in_groups_of(self.doubles ? 2 : 1, nil).each do |side| self.teams << Player.create(self,side) end end Which doesn't work. Should there maybe be a Game model that ties everything together rather than (my current method) defining the game as an abstraction via the relationships between Events, Users, and Rounds (and Teams and Players and etc.)? My head is swimming.

    Read the article

  • Is Form validation and Business validation too much?

    - by Robert Cabri
    I've got this question about form validation and business validation. I see a lot of frameworks that use some sort of form validation library. You submit some values and the library validates the values from the form. If not ok it will show some errors on you screen. If all goes to plan the values will be set into domain objects. Here the values will be or, better said, should validated (again). Most likely the same validation in the validation library. I know 2 PHP frameworks having this kind of construction Zend/Kohana. When I look at programming and some principles like Don't Repeat Yourself (DRY) and single responsibility principle (SRP) this isn't a good way. As you can see it validates twice. Why not create domain objects that do the actual validation. Example: Form with username and email form is submitted. Values of the username field and the email field will be populated in 2 different Domain objects: Username and Email class Username {} class Email {} These objects validate their data and if not valid throw an exception. Do you agree? What do you think about this aproach? Is there a better way to implement validations? I'm confused about a lot of frameworks/developers handling this stuff. Are they all wrong or am I missing a point? Edit: I know there should also be client side kind of validation. This is a different ballgame in my Opinion. If You have some comments on this and a way to deal with this kind of stuff, please provide.

    Read the article

  • How to model has_many with polymorphism?

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

    Read the article

  • Counting string length in javascript and Ruby on Rails

    - by williamjones
    I've got a text area on a web site that should be limited in length. I'm allowing users to enter 255 characters, and am enforcing that limit with a Rails validation: validates_length_of :body, :maximum => 255 At the same time, I added a javascript char counter like you see on Twitter, to give feedback to the user on how many characters he has already used, and to disable the submit button when over length, and am getting that length in Javascript with a call like this: element.length Lastly, to enforce data integrity, in my Postgres database, I have created this field as a varchar(255) as a last line of defense. Unfortunately, these methods of counting characters do not appear to be directly compatible. Javascript counts the best, in that it counts what users consider as number of characters where everything is a single character. Once the submission hits Rails, however, all of the carriage returns have been converted to \r\n, now taking up 2 characters worth of space, which makes a close call fail Rails validations. Even if I were to handcode a different length validation in Rails, it would still fail when it hits the database I think, though I haven't confirmed this yet. What's the best way for me to make all this work the way the user would want? Best Solution: an approach that would enable me to meet user expectations, where each character of any type is only one character. If this means increasing the length of the varchar database field, a user should not be able to sneakily send a hand-crafted post that creates a row with more than 255 letters. Somewhat Acceptable Solution: a javascript change that enables the user to see the real character count, such that hitting return increments the counter 2 characters at a time, while properly handling all symbols that might have these strange behaviors.

    Read the article

  • Disable validation in an object in Ruby on Rails

    - by J. Pablo Fernández
    I have an object which whether validation happens or not should depend on a boolean, or in another way, validation is optional. I haven't found a clean way to do it. What I'm currently doing is this (disclaimer: you cannot unsee, leave this page if you are too sensitive): def valid? if perform_validation super else super # Call valid? so that callbacks get called and things like encrypting passwords and generating salt in before_validation actually happen errors.clear # but then clear the errors true # and claim ourselves to be valid. This is super hacky! end end Any better ways? Before you point to the :if argument of many validations, this is for a user model which is using authlogic so it has a lot of validation rules. You can stop reading here if you belive me. If you don't, authlogic already sets some :ifs like: :if => :email_changed? which I have to turn into :if => Proc.new {|user| user.email_changed? and user.perform_validation} and in some other cases, since I'm also using authlogic-oid (OpenID) I just don't have control over the :if, authlogic-oid sets it in a way I cannot change it (in time) without further monkey patching. So I have to override seemingly unrelated functions, catch exceptions if a method doesn't exist, etc. The previous hacky solution if the best of my two attempts.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12  | Next Page >