Search Results

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

Page 38/70 | < Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >

  • Finds in Rails 3 and ActiveRelation

    - by TheDelChop
    Guys, I'm trying to understand the new arel engine in Rails 3 and I've got a question. I've got two models, User and Task class User < ActiveRecord::Base has_many :tasks end class Task < ActiveRecord::Base belongs_to :user end here is my routes to imply the relation: resources :users do resources :tasks end and here is my Tasks controller: class TasksController < ApplicationController before_filter :load_user def new @task = @user.tasks.new end private def load_user @user = User.where(:id => params[:user_id]) end end Problem is, I get the following error when I try to invoke the new action: NoMethodError: undefined method `tasks' for #<ActiveRecord::Relation:0x3dc2488> I am sure my problem is with the new arel engine, does anybody understand what I'm doing wrong? Sorry guys, here is my schema.db file: ActiveRecord::Schema.define(:version => 20100525021007) do create_table "tasks", :force => true do |t| t.string "name" t.integer "estimated_time" t.datetime "created_at" t.datetime "updated_at" t.integer "user_id" end create_table "users", :force => true do |t| t.string "email", :default => "", :null => false t.string "encrypted_password", :limit => 128, :default => "", :null => false t.string "password_salt", :default => "", :null => false t.string "reset_password_token" t.string "remember_token" t.datetime "remember_created_at" t.integer "sign_in_count", :default => 0 t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at" t.datetime "updated_at" t.string "username" end add_index "users", ["email"], :name => "index_users_on_email", :unique => true add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true add_index "users", ["username"], :name => "index_users_on_username", :unique => true end Thank you, Joe

    Read the article

  • ruby on rails one-to-many relationship

    - by fenec
    I would like to model a betting system relationship using the power of rails. so lets start with doing something very simple modelling the relationship from a user to a bet.i would like to have a model bet with 2 primary keys. here are my migrations enter code here class CreateBets < ActiveRecord::Migration def self.up create_table :bets do |t| t.integer :user_1_id t.integer :user_2_id t.integer :amount t.timestamps end end def self.down drop_table :bets end end class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :name t.timestamps end end def self.down drop_table :users end end the models enter code here class Bet < ActiveRecord::Base belongs_to :user_1,:class_name=:User belongs_to :user_2,:class_name=:User end class User < ActiveRecord::Base has_many :bets, :foreign_key =:user_1) has_many :bets, :foreign_key =:user_2) end when i test here in the console my relationships I got an error enter code here u1=User.create :name="aa" = # u2=User.create :name="bb" = # b=Bet.create(:user_1=u1,:user_2=u2) *****error***** QUESTIONS: 1 How do I define the relationships between these tables correctly? 2 are there any conventions to name the attributes (ex:user_1_id...) thank you for your help

    Read the article

  • Paperclip: Stay put on edit

    - by EricR
    When a user edits something in my application, they're forced to re-upload their image via paperclip even if they aren't changing it. Failing to do so will cause an error, since I validate_presence_of :image. This is quite annoying. How can I make it so Paperclip won't update its attributes if a user simply doesn't supply a new image on an edit? The photo controller is fresh out of Rails' scaffold generator. The rest of the source code is provided below. models/accommodation.rb class Accommodation < ActiveRecord::Base attr_accessible :photo validates_presence_of :photo has_one :photo has_many :notifications belongs_to :user accepts_nested_attributes_for :photo, :allow_destroy => true end controllers/accommodation_controller.rb class AccommodationsController < ApplicationController def index @accommodations = Accommodation.all end def show @accommodation = Accommodation.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:error] = "Accommodation not found." redirect_to :home end def new @accommodation = current_user.accommodations.build @accommodation.build_photo end def create @accommodation = current_user.accommodations.build(params[:accommodation]) if @accommodation.save flash[:notice] = "Successfully created your accommodation." redirect_to @accommodation else @accommodation.build_photo render :new end end def edit @accommodation = Accommodation.find(params[:id]) @accommodation.build_photo rescue ActiveRecord::RecordNotFound flash[:error] = "Accommodation not found." redirect_to :home end def update @accommodation = Accommodation.find(params[:id]) if @accommodation.update_attributes(params[:accommodation]) flash[:notice] = "Successfully updated accommodation." redirect_to @accommodation else @accommodation.build_photo render :edit end end def destroy @accommodation = Accommodation.find(params[:id]) @accommodation.destroy flash[:notice] = "Successfully destroyed accommodation." redirect_to :inkeep end end models/photo.rb class Photo < ActiveRecord::Base attr_accessible :image, :primary belongs_to :accommodation has_attached_file :image, :styles => { :thumb=> "100x100#", :small => "150x150>" } end

    Read the article

  • Mixing has_one and has_and_belongs_to_many associations

    - by Thomas
    I'm trying to build a database of urls(links). I have a Category model that has and belongs to many Links. Here's the migration I ran: class CreateLinksCategories < ActiveRecord::Migration def self.up create_table :links_categories, :id => false do |t| t.references :link t.references :category end end def self.down drop_table :links_categories end end Here's the Link model: class Link < ActiveRecord::Base validates :path, :presence => true, :format => { :with => /^(#{URI::regexp(%w(http https))})$|^$/ } validates :name, :presence => true has_one :category end Here's the category model: class Category < ActiveRecord::Base has_and_belongs_to_many :links end And here's the error the console kicked back when I tried to associate the first link with the first category: >>link = Link.first => #<Link id: 1, path: "http://www.yahoo.com", created_at: "2011-01-10... >>category = Category.first => #<category id : 1, name: "News Site", created_at: "2011-01-11... >>link.category << category => ActiveRecord::StatementInvalid: SQLite3::Exception: no such column : categories.link_id: Are my associations wrong or am I missing something in the database? I expected it to find the links_categories table. Any help is appreciated.

    Read the article

  • Database schema to store AND, OR relation, association

    - by user455387
    Many thanks for your help on this. In order for an entreprise to get a call for tender it must meet certain requirements. For the first example the enterprise must have a minimal class 4, and have qualification 2 in sector 5. Minimal class is always one number. Qualification can be anything (single, or multiple using AND, OR logical operators) I have created tables in order to map each number to it's given name. Now I need to store requirements in the database. minimal class 4 Sector Qualification 5.2 minimal class 2 Sector Qualifications 3.9 and 3.10 minimal class 3 Sector Qualifications 6.1 or 6.3 minimal class 1 Sector Qualifications (3.1 and 3.2) or 5.6 class Domain < ActiveRecord::Base has_many :domain_classes has_many :domain_sectors has_many :sector_qualifications, :through => :domain_sectors end class DomainClass < ActiveRecord::Base belongs_to :domain end class DomainSector < ActiveRecord::Base belongs_to :domain has_many :sector_qualifications end class SectorQualification < ActiveRecord::Base belongs_to :domain_sector end create_table "domains", :force => true do |t| t.string "name" end create_table "domain_classes", :force => true do |t| t.integer "number" t.integer "domain_id" end create_table "domain_sectors", :force => true do |t| t.string "name" t.integer "number" t.integer "domain_id" end create_table "sector_qualifications", :force => true do |t| t.string "name" t.integer "number" t.integer "domain_sector_id" end

    Read the article

  • How do I create a polymorphic model with a collection_select?

    - by muxe
    This are my models: class Speaker < ActiveRecord::Base belongs_to :session, :foreign_key => :session_id, :class_name => :Session belongs_to :speakable, :polymorphic => true end class Session < ActiveRecord::Base has_many :speakers accepts_nested_attributes_for :speakers end class Person < ActiveRecord::Base has_many :speakers, :as => :speakable end class Company < ActiveRecord::Base has_many :speakers, :as => :speakable end What I want to do now is something like this: app/views/sessions/edit.html.erb <% f.fields_for :speakers do |sf| %> <p> <%= sf.label :speaker %><br /> <%= sf.collection_select :speakable, Company.all + Person.all, :id, :full_name %> </p> <% end %> But it is not working because of the polymorphic assignment. How do I approach this problem? EDIT: The Error is: undefined method `base_class' for String:Class with params being: "speaker"=>{"speakable"=>"1063885469", "session_id"=>"1007692731"} The value passed to speakable is the id of the Speaker/Company. Yes, this is the value I specified the collection_select to return, but how can I manage to supply both values (speakable_id and speakable_type) ?

    Read the article

  • has_many :through default values

    - by David Lyod
    I have a need to design a system to track users memberships to groups with varying roles (currently three). class Group < ActiveRecord::Base has_many :memberships has_many :users, :through => :memberships end class Role < ActiveRecord::Base has_many :memberships has_many :users, :through => :memberships end class Membership < ActiveRecord::Base belongs_to :user belongs_to :role belongs_to :group end class User < ActiveRecord::Base has_many :memberships has_many :groups, :through => :memberships end Ideally what I want is to simply set @group.users << @user and have the membership have the correct role. I can use :conditions to select data that has been manually inserted as such : :conditions => ["memberships.grouprole_id= ? ", Grouprole.find_by_name('user')] But when creating the membership to the group the grouprole_id is not being set. Is there a way to do this as at present I have a somewhat repetitive piece of code for each user role in my Group model.

    Read the article

  • How do you deal with breaking changes in a Rails migration?

    - by Adam Lassek
    Let's say I'm starting out with this model: class Location < ActiveRecord::Base attr_accessible :company_name, :location_name end Now I want to refactor one of the values into an associated model. class CreateCompanies < ActiveRecord::Migration def self.up create_table :companies do |t| t.string :name, :null => false t.timestamps end add_column :locations, :company_id, :integer, :null => false end def self.down drop_table :companies remove_column :locations, :company_id end end class Location < ActiveRecord::Base attr_accessible :location_name belongs_to :company end class Company < ActiveRecord::Base has_many :locations end This all works fine during development, since I'm doing everything a step at a time; but if I try deploying this to my staging environment, I run into trouble. The problem is that since my code has already changed to reflect the migration, it causes the environment to crash when it attempts to run the migration. Has anyone else dealt with this problem? Am I resigned to splitting my deployment up into multiple steps?

    Read the article

  • Rails accepts_nested_attributes_for and build_attribute with polymorphic relationships

    - by SooDesuNe
    The core of this question is where build_attribute is required in a model with nested attribuites I'm working with a few models that are setup like: class Person < ActiveRecord::Base has_one :contact accepts_nested_attributes_for :contact, :allow_destroy=> true end class Contact < ActiveRecord::Base belongs_to :person has_one :address, :as=>:addressable accepts_nested_attributes_for :address, :allow_destroy=> true end class Address < ActiveRecord::Base belongs_to :addressable, :polymorphic=>true end I have to define the new method of people_controller like: def new @person = Person.new @person.build_contact @person.contact.build_address #!not very good encapsulation respond_to do |format| format.html # new.html.erb format.xml { render :xml => @person } end end Without @person.contact.build_address the address relationship on contact is NIL. I don't like having to build_address in people_controller. That should be handled by Contact. Where do I define this in Contact since the contacts_controller is not involved here?

    Read the article

  • What does this rake db:seed error mean?

    - by Kenji Kina
    I've been trying to solve this problem for a couple of hours but I can't seem to understand what's going on. I'm using Rails 3 beta, and want to seed some data to the database. However, when I try to seed some values through db:seed, I get this error: rake aborted! Attribute(#81402440) expected, got Array(#69024170) The seeds.rb is: DataType.delete_all DataType.create( :name => 'String' ) And I got these classes: class DataType < ActiveRecord::Base has_many :attributes end class Attribute < ActiveRecord::Base belongs_to :data_types end While the migration definition for DataType is merely: class CreateDataTypes < ActiveRecord::Migration def self.up create_table :data_types do |t| t.string :name t.timestamps end end def self.down drop_table :data_types end end Can anyone tell me what I'm doing wrong?

    Read the article

  • Rails eager loading

    - by Dimitar Vouldjeff
    HI, I have a Test model, which has_many questions, and Question, which has_many answers... When I make a query for a Test with :include = [:questions, {:questions = :answers}] ActiveRecord makes two more queries to fetch the questions and then to fetch the answers - it doesn`t join them!!! When I do the query with :joins ActiveRecord makes the query, but later when I need the Test.questions or Test.questions.answers ActiveRecord makes again those 2 extra queries!!! And later when I enumerate the questions or answers in the log I see other queries for each object, but it has Cache tag... Is this normal?

    Read the article

  • Is it legal to stub the #class method of a Mock object when using RSpec in a Ruby on Rails applicati

    - by MiniQuark
    I would like to stub the #class method of a mock object: describe Letter do before(:each) do @john = mock("John") @john.stub!(:id).and_return(5) @john.stub!(:class).and_return(Person) # is this ok? @john.stub!(:name).and_return("John F.") Person.stub!(:find).and_return(@john) end it.should "have a valid #to field" do letter = Letter.create!(:to=>@john, :content => "Hello John") letter.to_type.should == @john.class.name letter.to_id.should == @john.id end [...] end On line 5 of this program, I stub the #class method, in order to allow things like @john.class.name. Is this the right way to go? Will there be any bad side effect? Edit: The Letter class looks like this: class Letter < ActiveRecord::Base belongs_to :to, :polymorphic => true [...] end I wonder whether ActiveRecord gets the :to field's class name with to.class.name or by some other means. Maybe this is what the class_name method is ActiveRecord::Base is for?

    Read the article

  • Rails HABTM Scoping to current subdomain

    - by Rabbott
    I have the following associations: class User < ActiveRecord::Base has_and_belongs_to_many :brands, :join_table => 'brands_users' has_and_belongs_to_many :companies, :join_table => 'companies_users' end class Brand < ActiveRecord::Base belongs_to :company has_and_belongs_to_many :users, :join_table => 'brands_users' end class Company < ActiveRecord::Base has_and_belongs_to_many :users, :join_table => 'companies_users' has_many :brands, :order => :name end While editing a user I am using the checkbox list of brands. So that I can assign users 'access' to brands, the brands that show up are only the brands that belong to the current company (defined by the subdomain [using subdomain_fu]). The problem I am running into is that when using the default HABTM functionality and the checkbox list, upon save, Rails removes ALL user-brand associations, then re-adds just the ones for the form I just submitted.. How do I scope that to only remove associations of brands who belong to the current company, defined in the subdomain?

    Read the article

  • Acts as Tree with Multiple Models

    - by Joe
    I've got several models that I'd like to relate together hierarchically. For simplicity's sake, let's say I've got these three: class Group < ActiveRecord::Base acts_as_tree has_many :users end class User < ActiveRecord::Base acts_as_tree belongs_to :group has_many :posts end class Post < ActiveRecord::Base acts_as_tree belongs_to :user end Under the current acts_as_tree, each node can individually can relate hierarchically to other nodes provided they are of the same type. What I'd like is to remove this restriction on type identity, so that SomePost.parent could have a User or a Post as its' parent, and that SomeUser.parent could have another user or a group as its parent. Any thoughts?

    Read the article

  • how to model a many to many relationship

    - by Maulin
    Here is the scenario, Articles have many Comments Users can write many Comments for many Articles The comments table contains both user_id article_id as foreign keys My models are set up like so class User < ActiveRecord::Base has_many :comments has_many :articles, :through => :comments class Article < ActiveRecord::Base has_many :comments has_many :users, :through => :comments class Comment < ActiveRecord::Base belongs_to :users belongs_to :articles My routes.rb has the following code map.resources :articles, :has_many => :comments map.resources :users, :has_many => :comments which produces the following routes new_article_comment edit_article_comment new_user_comment edit_user_comment etc... This is not what I want (atleast not what I think I want), since comments must always be related to users and article, how can I get a route like so new_user_article_comment edit_user_article_comment Then I could just do new_user_article_comment_path([@user, @article]) to create a new comment

    Read the article

  • Rails 3 find all associated records has_many :through

    - by Sergey
    I would like to list all posts that are connected with some specific category. I have: class Post < ActiveRecord::Base has_many :category_posts has_many :categories, :through => :category_posts end class Category < ActiveRecord::Base has_many :category_posts has_many :posts, :through => :category_posts end class CategoryPost < ActiveRecord::Base belongs_to :category belongs_to :post end And I wanna do something like this Post.where(["category.id = ?", params[:category_id]]) It indeed is very simple task, but I don't know what I should be looking for (keywords). It's the same problem like this, but in rails.

    Read the article

  • Possible to see what actual SQL queries Rails invokes when using console script?

    - by randombits
    Sometimes I like to pop open the console script that comes with Rails to test small excerpts of code. That code normally involves some more involved ActiveRecord queries. Although not an expert in ActiveRecord, I'm proficient with SQL and want to see what it's translating underneath the hood for efficiency purposes. This will help me refactor or rethink how I'm writing my app if it looks inefficient. Now when the query is in the actual application itself, it all shows up in logs. Ad-hoc ActiveRecord queries in the console do not though. Anyway to change that behavior?

    Read the article

  • No method error in controller create action

    - by user2799827
    I have read a number of Q&As on SO in search of some help on this but have so far not solved my issue. I am trying to teach myself ruby/rails, and as a test project, I want to create a list of tvshows and a list of characters where each tvshow has_many characters and each character belongs_to a specific show. I am sure I am doing something basic incorrectly. Any assistance would be greatly appreciated. here is the characters controller: class CharactersController < ApplicationController before_action :set_character, only: [:show, :edit, :update, :destroy] # GET /characters # GET /characters.json def index @characters = Character.all end # GET /characters/1 # GET /characters/1.json def show end # GET /characters/new def new @character = Character.new end # GET /characters/1/edit def edit end # POST /characters # POST /characters.json def create @character = @tvshow.characters.create(params[:character]) respond_to do |format| if @character.save format.html { redirect_to @character, notice: 'Character was successfully created.' } format.json { render action: 'show', status: :created, location: @character } else format.html { render action: 'new' } format.json { render json: @character.errors, status: :unprocessable_entity } end end end # PATCH/PUT /characters/1 # PATCH/PUT /characters/1.json def update respond_to do |format| if @character.update(character_params) format.html { redirect_to @character, notice: 'Character was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @character.errors, status: :unprocessable_entity } end end end # DELETE /characters/1 # DELETE /characters/1.json def destroy @character.destroy respond_to do |format| format.html { redirect_to characters_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_character @character = Character.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def character_params params.require(:character).permit(:first_name, :last_name, :bio) end end character model: class Character < ActiveRecord::Base belongs_to :tvshow default_scope -> { order('created_at DESC') } validates :tvshow_id, presence: true end tvshow model: class Tvshow < ActiveRecord::Base has_many :characters, dependent: :destroy end error gets returned when I attempt to create a character. here is the full trace: app/controllers/characters_controller.rb:27:in `create' actionpack (4.0.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action' actionpack (4.0.0) lib/abstract_controller/base.rb:189:in `process_action' actionpack (4.0.0) lib/action_controller/metal/rendering.rb:10:in `process_action' actionpack (4.0.0) lib/abstract_controller/callbacks.rb:18:in `block in process_action' activesupport (4.0.0) lib/active_support/callbacks.rb:413:in `_run__1211653665462320621__process_action__callbacks' activesupport (4.0.0) lib/active_support/callbacks.rb:80:in `run_callbacks' actionpack (4.0.0) lib/abstract_controller/callbacks.rb:17:in `process_action' actionpack (4.0.0) lib/action_controller/metal/rescue.rb:29:in `process_action' actionpack (4.0.0) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action' activesupport (4.0.0) lib/active_support/notifications.rb:159:in `block in instrument' activesupport (4.0.0) lib/active_support/notifications/instrumenter.rb:20:in `instrument' activesupport (4.0.0) lib/active_support/notifications.rb:159:in `instrument' actionpack (4.0.0) lib/action_controller/metal/instrumentation.rb:30:in `process_action' actionpack (4.0.0) lib/action_controller/metal/params_wrapper.rb:245:in `process_action' activerecord (4.0.0) lib/active_record/railties/controller_runtime.rb:18:in `process_action' actionpack (4.0.0) lib/abstract_controller/base.rb:136:in `process' actionpack (4.0.0) lib/abstract_controller/rendering.rb:44:in `process' actionpack (4.0.0) lib/action_controller/metal.rb:195:in `dispatch' actionpack (4.0.0) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch' actionpack (4.0.0) lib/action_controller/metal.rb:231:in `block in action' actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:80:in `call' actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:80:in `dispatch' actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:48:in `call' actionpack (4.0.0) lib/action_dispatch/journey/router.rb:71:in `block in call' actionpack (4.0.0) lib/action_dispatch/journey/router.rb:59:in `each' actionpack (4.0.0) lib/action_dispatch/journey/router.rb:59:in `call' actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:655:in `call' rack (1.5.2) lib/rack/etag.rb:23:in `call' rack (1.5.2) lib/rack/conditionalget.rb:35:in `call' rack (1.5.2) lib/rack/head.rb:11:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/params_parser.rb:27:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/flash.rb:241:in `call' rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context' rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/cookies.rb:486:in `call' activerecord (4.0.0) lib/active_record/query_cache.rb:36:in `call' activerecord (4.0.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in `call' activerecord (4.0.0) lib/active_record/migration.rb:369:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' activesupport (4.0.0) lib/active_support/callbacks.rb:373:in `_run__2792846465963916895__call__callbacks' activesupport (4.0.0) lib/active_support/callbacks.rb:80:in `run_callbacks' actionpack (4.0.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/reloader.rb:64:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/remote_ip.rb:76:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' railties (4.0.0) lib/rails/rack/logger.rb:38:in `call_app' railties (4.0.0) lib/rails/rack/logger.rb:21:in `block in call' activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `block in tagged' activesupport (4.0.0) lib/active_support/tagged_logging.rb:25:in `tagged' activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `tagged' railties (4.0.0) lib/rails/rack/logger.rb:21:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/request_id.rb:21:in `call' rack (1.5.2) lib/rack/methodoverride.rb:21:in `call' rack (1.5.2) lib/rack/runtime.rb:17:in `call' activesupport (4.0.0) lib/active_support/cache/strategy/local_cache.rb:83:in `call' rack (1.5.2) lib/rack/lock.rb:17:in `call' actionpack (4.0.0) lib/action_dispatch/middleware/static.rb:64:in `call' railties (4.0.0) lib/rails/engine.rb:511:in `call' railties (4.0.0) lib/rails/application.rb:97:in `call' rack (1.5.2) lib/rack/lock.rb:17:in `call' rack (1.5.2) lib/rack/content_length.rb:14:in `call' rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service' /Users/dariusgoore/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service' /Users/dariusgoore/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run' /Users/dariusgoore/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'

    Read the article

  • Validates presence of each other in two associated models

    - by Sergey Alekseev
    I have the following two models: class Parent < ActiveRecord::Base has_one :child, dependent: :destroy validates :child, presence: true end class Child < ActiveRecord::Base belongs_to :parent validates :parent, presence: true end I want to create Parent object. If I do the following: Parent.create! or Factory(:parent) Exception raises: ActiveRecord::RecordInvalid: Validation failed: Child can't be blank But I can't create Child object without Parent object for the same reason - I need to create Parent object first in order to pass presence validation. As it appears I have some kind of infinite recursion here. How to solve it?

    Read the article

  • User HasOne ActiveToken, HasMany Tokens, how to setup in Rails?

    - by viatropos
    I have two simple models: class User < ActiveRecord::Base has_many :tokens # has_one doesn't work, because Token already stores # foreign id to user... # has_one :active_token, :class_name => "Token" # belongs_to doesn't work because Token belongs to # User already, and they both can't belong to each other # belongs_to :active_token, :class_name => "Token" end class Token < ActiveRecord::Base belongs_to :user end I want to say "User has_one :active_token, :class_name => 'Token'", but I can't because Token already belongs_to User. What I did instead was just manually add similar functionality to the user like so: class User < ActiveRecord::Base has_many :tokens attr_accessor :active_token after_create :save_active_token before_destroy :destroy_active_token # it belongs_to, but you can't have both belongs_to each other... def active_token return nil unless self.active_token_id @active_token ||= Token.find(self.active_token_id) end def active_token=(value) self.active_token_id = value.id @active_token = value end def save_active_token self.active_token.user = self self.active_token.save end def destroy_active_token self.active_token.destroy if self.active_token end end Is there a better way?

    Read the article

  • How to clone a model's attributes easily?

    - by Zabba
    I have these models: class Address < ActiveRecord::Base belongs_to :event attr_accessible :street, :city validates :street, :city, :presence => true end class Event < ActiveRecord::Base has_one :address accepts_nested_attributes_for :address end If I do the below assignment in the Events create action and save the event I get an error: #Use the current user's address for the event @event.address_attributes = current_user.address.attributes #Error occurs at the above mentioned line ActiveRecord::RecordNotFound (Couldn't find Address with ID=1 for Event with ID=) I think what's happening is that all the address's attributes (including the primary key) is getting assigned in the @event.address_attributes = line. But all I really want is the "real data" (street, city), not the primary keys or created_at etc to get copied over. I suppose I could write a small method to do this sort of selective copy but I can't help but feel there must be some built-in method for this? What's the best/right way to do this?

    Read the article

  • Creating an instance in rails association

    - by Sandeep Rao
    I have three models where a basiccase has a form. Basic case can create a new form. class User < ActiveRecord::Base has_many :basiccases end class Basiccase < ActiveRecord::Base belongs_to :user has_one :basiccases end class Form3C < ActiveRecord::Base belongs_to :basiccases end I want to create an instance of form 3c in the form3c controller. Can any one explain me how I can carry the basiccase_id to the form3c controller to set the foreign key attribute. I can set the value using @basiccase.build_form3_c but I'm not sure how I can get the basiccase_id from the basiccase.

    Read the article

  • Rails - How to secure foreign keys and still allow association selection

    - by Bryce
    For simplicity, assume that I have a simple has-many-through relationship class User < ActiveRecord::Base has_many :courses, :through => :registrations end class Registration < ActiveRecord::Base belongs_to :user belongs_to :course end class Course < ActiveRecord::Base has_many :users, :through => :registrations end I want to keep my app secure, so I use attr_accessible to whitelist my attributes. My question is twofold: How would I set up my whitelist attributes such that I could create a new Registration object through a form (passing in :user and :course, but not risk allowing those foreign keys to be maliciously updated later? How would I set up my validations such that both belongs_to associations are required BUT also allow for Registration objects to be created in nested forms?

    Read the article

  • Problem building relationships between models

    - by Brian Roisentul
    Until now, I've been using acts_as_taggable_on plugin for tagging announcements. That plugin creates the following tables: taggings: relates tags and announcements table(for the tagged item, it has a field called taggable_id, which I rename to "announcement_id" for what I'll explain below). tags: has the tag ids and names. The other day, I discovered that I had no way of getting the announcements tagged with a certain tag, but doing Announcement.tagged_with(tag_name), and I don't want to search by name, but for id. So, as I'm using almost nothing of the functionality in that plugin, I decided to create the models for taggings and tags tables, to accomplish this: Announcement.tags. The models' relationships look as following: class Tagging < ActiveRecord::Base belongs_to :announcement belongs_to :tag end class Tag < ActiveRecord::Base has_many :announcements, :through => :taggings end class Announcement < ActiveRecord::Base has_many :tags, :through => :taggings Why can't I execute the command Announcement.tags? Because when I try, I get undefined method `tags'

    Read the article

  • Nested form child only updates if parent changes.

    - by chap
    In this video (10 sec) you can see that the nested attribute is only updated if it's parent model is changed. Using rails 3.0.0.beta and full project is on github. Summary of models and form: class Project < ActiveRecord::Base has_many :tasks accepts_nested_attributes_for :tasks end class Task < ActiveRecord::Base belongs_to :project has_many :assignments accepts_nested_attributes_for :assignments end class Assignment < ActiveRecord::Base belongs_to :task end form_for(@project) do |f| Project: f.text_field :name f.fields_for :tasks do |task_form| Task: task_form.text_field :name task_form.fields_for :assignments do |assignment_form| Assignment: assignment_form.text_field :name end end f.submit end

    Read the article

< Previous Page | 34 35 36 37 38 39 40 41 42 43 44 45  | Next Page >