Search Results

Search found 676 results on 28 pages for 'polymorphic associations'.

Page 1/28 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Rails polymorphic associations, two assoc types in one class

    - by snitko
    Consider a class: class Link < ActiveRecord::Base has_many :link_votes, :as => :vote_subject, :class_name => 'Vote' has_many :spam_votes, :as => :vote_subject, :class_name => 'Vote' end The problem is, when I'm adding a new vote with @link.link_votes << Vote.new the vote_subject_type is 'Link', while I wish it could be 'link_votes' or something like that. Is this an AR limitation or is there a way to workaround this thing? I've actually found one related answer, but I'm not quite sure about what it says: http://stackoverflow.com/questions/1168047/polymorphic-association-with-multiple-associations-on-the-same-model/1764117#1764117

    Read the article

  • Using Ruby on Rails, can a polymorphic database be created in a few steps (with polymorphic associat

    - by Jian Lin
    I thought it could be created in a few steps but it can't yet: rails poly cd poly ruby script/generate scaffold animal name:string obj_type:string obj_id:integer rake:migrate ruby script/generate scaffold human name:string passportNumber:string rake:migrate ruby script/generate scaffold dog name:string registrationNumber:string rake:migrate and now change app/models/animal.rb to: class Animal < ActiveRecord::Base belongs_to :obj, :polymorphic => true end and run ruby script/server and go to http://localhost:3000 I thought on the server then if I create an Michael, Human, J123456 and then Woofie, Dog, L23456 then the database will have entries in the Dogs table and "Humen" or "Humans" table as well as in the Animals table? But only the Animals table has records, Dogs and "Humen" do not for some reason. Is there some steps missing?

    Read the article

  • Rails Polymorphic Association with multiple associations on the same model

    - by Matt Rogish
    My question is essentially the same as this one: http://stackoverflow.com/questions/1168047/polymorphic-association-with-multiple-associations-on-the-same-model However, the proposed/accepted solution does not work, as illustrated by a commenter later. I have a Photo class that is used all over my app. A post can have a single photo. However, I want to re-use the polymorphic relationship to add a secondary photo. Before: class Photo belongs_to :attachable, :polymorphic => true end class Post has_one :photo, :as => :attachable, :dependent => :destroy end Desired: class Photo belongs_to :attachable, :polymorphic => true end class Post has_one :photo, :as => :attachable, :dependent => :destroy has_one :secondary_photo, :as => :attachable, :dependent => :destroy end However, this fails as it cannot find the class "SecondaryPhoto". Based on what I could tell from that other thread, I'd want to do: has_one :secondary_photo, :as => :attachable, :class_name => "Photo", :dependent => :destroy Except calling Post#secondary_photo simply returns the same photo that is attached via the Photo association, e.g. Post#photo === Post#secondary_photo. Looking at the SQL, it does WHERE type = "Photo" instead of, say, "SecondaryPhoto" as I'd like... Thoughts? Thanks!

    Read the article

  • Caching a column in a polymorphic relationship

    - by Brendon Muir
    I have content management system application that uses a polymorphic tree table as the core of its arrangement. I've come into a problem where once the tree grows quite large, and because we have quite a few different modules (about 25), just doing :include = :instance doesn't cut the mustard. Instance is the name of our polymorphic relationship. The funny part is that in most cases when I want a large list of these items, all I really want is their name from the associated table (for the purposes of an index bar for example), all the rest is in the central table. So I thought that I should probably implement some sort of column cache for the name in the central table. (Like a counter cache that rails already does). I was just wondering if a plugin exists to manage this already? If not, I was just going to add a 'name' column to the central table and because all the polymorphic models inherit off a superclass, just add a callback that pushes the name across to the central table whenever the item is created or updated. I'd then just do a big migration to populate it in the first place? Any flaws to that design? I suppose to be more flexible the column could be some kind of serialised cache where I could store other things later on if need be? Gah! :D

    Read the article

  • Problem with eager load polymorphic associations using Linq and NHibernate

    - by Voislav
    Is it possible to eagerly load polymorphic association using Linq and NH? For example: Company is base class, Department is inherited from Company, and Company has association Employees to the User (one-to-many) and also association to the Country (many-to-one). Here is mapping part related to inherited class (without User and Country classes): <class name="Company" discriminator-value="Company"> <id name="Id" type="int" unsaved-value="0" access="nosetter.camelcase-underscore"> <generator class="native"></generator> </id> <discriminator column="OrganizationUnit" type="string" length="10" not-null="true"/> <property name="Name" type="string" length="50" not-null="true"/> <many-to-one name="Country" class="Country" column="CountryId" not-null ="false" foreign-key="FK_Company_CountryId" access="field.camelcase-underscore" /> <set name="Departments" inverse="true" lazy="true" access="field.camelcase-underscore"> <key column="DepartmentParentId" not-null="false" foreign-key="FK_Department_DepartmentParentId"></key> <one-to-many class="Department"></one-to-many> </set> <set name="Employees" inverse="true" lazy="true" access="field.camelcase-underscore"> <key column="CompanyId" not-null="false" foreign-key="FK_User_CompanyId"></key> <one-to-many class="User"></one-to-many> </set> <subclass name="Department" extends="Company" discriminator-value="Department"> <many-to-one name="DepartmentParent" class="Company" column="DepartmentParentId" not-null ="false" foreign-key="FK_Department_DepartmentParentId" access="field.camelcase-underscore" /> </subclass> </class> I do not have problem to eagerly load any of the association on the Company: Session.Query<Company>().Where(c => c.Name == "Main Company").Fetch(c => c.Country).Single(); Session.Query<Company>().Where(c => c.Name == "Main Company").FetchMany(c => c.Employees).Single(); Also, I could eagerly load not-polymorphic association on the department: Session.Query<Department>().Where(d => d.Name == "Department 1").Fetch(d => d.DepartmentParent).Single(); But I get NullReferenceException when I try to eagerly load any of the polymorphic association (from the Department): Assert.Throws<NullReferenceException>(() => Session.Query<Department>().Where(d => d.Name == "Department 1").Fetch(d => d.Country).Single()); Assert.Throws<NullReferenceException>(() => Session.Query<Department>().Where(d => d.Name == "Department 1").FetchMany(d => d.Employees).Single()); Am I doing something wrong or this is not supported yet?

    Read the article

  • Rails AR validates_uniqueness_of against polymorphic relationship

    - by aaronrussell
    Is it posible to validate the uniqueness of a child model's attribute scoped against a polymorphic relationship? For example I have a model called field that belongs to fieldable: class Field < ActiveRecord::Base belongs_to :fieldable, :polymorphic => :true validates_uniqueness_of :name, :scope => :fieldable_id end I have several other models (Pages, Items) which have many Fields. So what I want is to validate the uniqueness of the field name against the parent model, but the problem is that occasionally a Page and an Item share the same ID number, causing the validations to fail when they shouldn't. Am I just doing this wrong or is there a better way to do this?

    Read the article

  • Creating an AJAX Form for a Polymorphic Object in Rails

    - by Isaac Yerushalmi
    I am trying to create an AJAX form for a polymorphic associated model. I created "Comments" which have a polymorphic association with all objects you can comment on (i.e. user profiles, organization profiles, events, etc). I can currently add comments to objects using a form created by: form_for [@commentable, @comment] do |f| I am trying to make this form via Ajax but I keep getting errors. I've tried at least ten different pieces of code, using remote_form_tag, remote_form_for, etc..with all different options, and nothing works. The comment does not get inserted into the database. Can anyone please tell me how I can make the above form ajax-enabled?

    Read the article

  • nested attributes with polymorphic has_one model

    - by Millisami
    I am using accepts_nested_attributes_for with the has_one polymorphic model in rails 2.3.5 Following are the models and its associations: class Address < ActiveRecord::Base attr_accessible :city, :address1, :address2 belongs_to :addressable, :polymorphic => true validates_presence_of :address1, :address2, :city end class Vendor < ActiveRecord::Base attr_accessible :name, :address_attributes has_one :address, :as => :addressable, :dependent => :destroy accepts_nested_attributes_for :address end This is the view: - form_for @vendor do |f| = f.error_messages %p = f.label :name %br = f.text_field :name - f.fields_for :address_attributes do |address| = render "shared/address_fields", :f => address %p = f.submit "Create" This is the partial shared/address_fields.html.haml %p = f.label :city %br= f.text_field :city %span City/Town name like Dharan, Butwal, Kathmandu, .. %p = f.label :address1 %br= f.text_field :address1 %span City Street name like Lazimpat, New Road, .. %p = f.label :address2 %br= f.text_field :address2 %span Tole, Marg, Chowk name like Pokhrel Tole, Shanti Marg, Pako, .. And this is the controller: class VendorsController < ApplicationController def new @vendor = Vendor.new end def create @vendor = Vendor.new(params[:vendor]) if @vendor.save flash[:notice] = "Vendor created successfully!" redirect_to @vendor else render :action => 'new' end end end The problem is when I fill in all the fileds, the record gets save on both tables as expected. But when I just the name and city or address1 filed, the validation works, error message shown, but the value I put in the city or address1, is not persisted or not displayed inside the address form fields? This is the same case with edit action too. Though the record is saved, the address doesn't show up on the edit form. Only the name of the Client model is shown. Actually, when I look at the log, the address model SQL is not queried even at all.

    Read the article

  • active_admin/formtastic ignoring polymorphic associations

    - by James Maskell
    I'm currently having trouble with the form for a polymorphic association in active_admin in Ruby on Rails. I have three models set up: offices, companies and users. Both companies and users can own an office. My models are set up as follows: class Office < ActiveRecord::Base belongs_to :ownable, :polymorphic => true end class User < ActiveRecord::Base has_many :offices, :as => :ownable end class Company < ActiveRecord::Base has_many :offices, :as => :ownable end active_admin doesn't allow me to edit the owner on its forms, but does show it correctly on the index and show pages (including links to the company or user). I've tried playing with formtastic to manually create the form but have not had any luck - the "ownable" fields just get ignored and everything else renders properly. To be clear: I want to be able to edit the owner of the Office model on the new and edit fields in active_admin. Can anyone offer any help? :)

    Read the article

  • Polymorphic associations in CakePHP2

    - by Joseph
    I have 3 models, Page , Course and Content Page and Course contain meta data and Content contains HTML content. Page and Course both hasMany Content Content belongsTo Page and Course To avoid having page_id and course_id fields in Content (because I want this to scale to more than just 2 models) I am looking at using Polymorphic Associations. I started by using the Polymorphic Behavior in the Bakery but it is generating waaay too many SQL queries for my liking and it's also throwing an "Illegal Offset" error which I don't know how to fix (it was written in 2008 and nobody seems to have referred to it recently so perhaps the error is due to it not having been designed for Cake 2?) Anyway, I've found that I can almost do everything I need by hardcoding the associations in the models as such: Page Model CREATE TABLE `pages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `updated` datetime NOT NULL, PRIMARY KEY (`id`) ) <?php class Page extends AppModel { var $name = 'Page'; var $hasMany = array( 'Content' => array( 'className' => 'Content', 'foreignKey' => 'foreign_id', 'conditions' => array('Content.class' => 'Page'), ) ); } ?> Course Model CREATE TABLE `courses` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `updated` datetime NOT NULL, PRIMARY KEY (`id`) ) <?php class Course extends AppModel { var $name = 'Course'; var $hasMany = array( 'Content' => array( 'className' => 'Content', 'foreignKey' => 'foreign_id', 'conditions' => array('Content.class' => 'Course'), ) ); } ?> Content model CREATE TABLE IF NOT EXISTS `contents` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `class` varchar(30) COLLATE utf8_unicode_ci NOT NULL, `foreign_id` int(11) unsigned NOT NULL, `title` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `content` text COLLATE utf8_unicode_ci NOT NULL, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) <?php class Content extends AppModel { var $name = 'Content'; var $belongsTo = array( 'Page' => array( 'foreignKey' => 'foreign_id', 'conditions' => array('Content.class' => 'Page') ), 'Course' => array( 'foreignKey' => 'foreign_id', 'conditions' => array('Content.class' => 'Course') ) ); } ?> The good thing is that $this->Content->find('first') only generates a single SQL query instead of 3 (as was the case with the Polymorphic Behavior) but the problem is that the dataset returned includes both of the belongsTo models, whereas it should only really return the one that exists. Here's how the returned data looks: array( 'Content' => array( 'id' => '1', 'class' => 'Course', 'foreign_id' => '1', 'title' => 'something about this course', 'content' => 'The content here', 'created' => null, 'modified' => null ), 'Page' => array( 'id' => null, 'title' => null, 'slug' => null, 'created' => null, 'updated' => null ), 'Course' => array( 'id' => '1', 'title' => 'Course name', 'slug' => 'name-of-the-course', 'created' => '2012-10-11 00:00:00', 'updated' => '2012-10-11 00:00:00' ) ) I only want it to return one of either Page or Course depending on which one is specified in Content.class UPDATE: Combining the Page and Course models would seem like the obvious solution to this problem but the schemas I have shown above are just shown for the purpose of this question. The actual schemas are actually very different in terms of their fields and the each have a different number of associations with other models too. UPDATE 2 Here is the query that results from running $this->Content->find('first'); : SELECT `Content`.`id`, `Content`.`class`, `Content`.`foreign_id`, `Content`.`title`, `Content`.`slug`, `Content`.`content`, `Content`.`created`, `Content`.`modified`, `Page`.`id`, `Page`.`title`, `Page`.`slug`, `Page`.`created`, `Page`.`updated`, `Course`.`id`, `Course`.`title`, `Course`.`slug`, `Course`.`created`, `Course`.`updated` FROM `cakedb`.`contents` AS `Content` LEFT JOIN `cakedb`.`pages` AS `Page` ON (`Content`.`foreign_id` = `Page`.`id` AND `Content`.`class` = 'Page') LEFT JOIN `cakedb`.`courses` AS `Course` ON (`Content`.`foreign_id` = `Course`.`id` AND `Content`.`class` = 'Course') WHERE 1 = 1 LIMIT 1

    Read the article

  • Ruby on Rails and database associations

    - by Marco
    Hi to all, I'm new to the Ruby world, and there is something unclear to me in defining associations between models. The question is: where is the association saved? For example, if i create a Customer model by executing: generate model Customer name:string age:integer and then i create an Order model generate model Order description:text quantity:integer and then i set the association in the following way: class Customer < ActiveRecord::Base has_many :orders end class Order < ActiveRecord::Base belongs_to :customer end I think here is missing something, for example the foreign key between the two entities. How does it handle the associations created with the keywords "has_many" and "belongs_to" ? Thanks

    Read the article

  • sti and polymorphic's

    - by Alexey Poimtsev
    Hi, I have problem with my code class Post < ActiveRecord::Base end class NewsArticle < Post has_many :comments, :as => :commentable, :dependent => :destroy, :order => 'created_at' end class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true, :counter_cache => true end And on attempt go get comments for some NewsArticle i see in logs something like Comment Load (0.9ms) SELECT "comments".* FROM "comments" WHERE ("comments"."commentable_id" = 1 and "comments"."commentable_type" = 'Post') ORDER BY created_at Strange that "commentable_type" = 'Post'. Whats wrong? PS: Rails 2.3.5 && ruby 1.8.7 (2010-01-10 patchlevel 249) [i686-darwin10]

    Read the article

  • Rails preventing duplicates in polymorphic has_many :through associations

    - by seaneshbaugh
    Is there an easy or at least elegant way to prevent duplicate entries in polymorphic has_many through associations? I've got two models, stories and links that can be tagged. I'm making a conscious decision to not use a plugin here. I want to actually understand everything that's going on and not be dependent on someone else's code that I don't fully grasp. To see what my question is getting at, if I run the following in the console (assuming the story and tag objects exist in the database already) s = Story.find_by_id(1) t = Tag.find_by_id(1) s.tags << t s.tags << t My taggings join table will have two entries added to it, each with the same exact data (tag_id = 1, taggable_id = 1, taggable_type = "Story"). That just doesn't seem very proper to me. So in an attempt to prevent this from happening I added the following to my Tagging model: before_validation :validate_uniqueness def validate_uniqueness taggings = Tagging.find(:all, :conditions => { :tag_id => self.tag_id, :taggable_id => self.taggable_id, :taggable_type => self.taggable_type }) if !taggings.empty? return false end return true end And it works almost as intended, but if I attempt to add a duplicate tag to a story or link I get an ActiveRecord::RecordInvalid: Validation failed exception. It seems that when you add an association to a list it calls the save! (rather than save sans !) method which raises exceptions if something goes wrong rather than just returning false. That isn't quite what I want to happen. I suppose I can surround any attempts to add new tags with a try/catch but that goes against the idea that you shouldn't expect your exceptions and this is something I fully expect to happen. Is there a better way of doing this that won't raise exceptions when all I want to do is just silently not save the object to the database because a duplicate exists?

    Read the article

  • Associating Models with Polymorphic

    - by Josh Crowder
    I am trying to associate Contacts with Classes but as two different types. Current_classes and Interested_classes. I know I need to enable polymorphic but I am not sure as to where it needs to be enabled. This is what I have at the moment class CreateClasses < ActiveRecord::Migration def self.up create_table :classes do |t| t.string :class_type t.string :class_name t.string :date t.timestamps end end def self.down drop_table :classes end end class CreateContactsInterestedClassesJoin < ActiveRecord::Migration def self.up create_table 'contacts_interested_classes', :id => false do |t| t.column 'class_id', :integer t.column 'contact_id', :integer end end def self.down drop_table 'contacts_interested_classes' end end class CreateContactsCurrentClassesJoin < ActiveRecord::Migration def self.up create_table 'contacts_current_classes', :id => false do |t| t.column 'class_id', :integer t.column 'contact_id', :integer end end def self.down drop_table 'contacts_current_classes' end end And then inside of my Contacts Model I want to have something like this. class Contact < ActiveRecord::Base has_and_belongs_to_many :classes, :join_table => "contacts_interested_classes", :foreign_key => "class_id" :as => 'interested_classes' has_and_belongs_to_many :classes, :join_table => "contacts_current_classes", :foreign_key => "class_id" :as => 'current_classes' end What am I doing wrong?

    Read the article

  • CanCan polymorphic resource access problem

    - by Call 'naive' True
    Hi everybody, i don't quite understand how to restrict access to links in this particular case with CanCan. I always get "Edit" link displayed. So i believe the problem is in my incorrect definition of cancan methods(load_ and authorize_). I have CommentsController like that: class CommentsController < ApplicationController before_filter :authenticate_user! load_resource :instance_name => :commentable authorize_resource :article def index @commentable = find_commentable #loading our generic object end ...... private def find_commentable params.each { |name, value| if name =~ /(.+)_id$/ return $1.classify.constantize.includes(:comments => :karma).find(value) end } end end and i have in comments/index.html.erb following code that render file from other controller: <%= render :file => "#{get_commentable_partial_name(@commentable)}/show.html.erb", :collection => @commentable %> you can think about "#{get_commentable_partial_name(@commentable)}" like just "articles" in this case. Content of "articles/show.html.erb": <% if can? :update, @commentable %> <%= link_to 'Edit', edit_article_path(@commentable) %> | <% end %> my ability.rb: class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user if user.role? :admin can :manage, :all elsif user.role? :author can :read, [Article, Comment, Profile] can :update, Article, :user_id => user.id end end end relations with models is: class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true, :dependent => :destroy ... end class Article < ActiveRecord::Base has_many :comments, :as => :commentable, :dependent => :destroy ... end i have tried debug this issue like that user = User.first article = Article.first ability = Ability.new(user) ability.can?(:update, article) and i always get "= true" in ability check Note: user.role == author and article.user_id != user.id if you need more information please write thank's for your time && sorry for my english

    Read the article

  • Rails Associations Question

    - by Mutuelinvestor
    I'm new to rails and have volunteered to help out the local High School Track team with a simple database that tracks the runners performances. For the moment, I have three models: Runners, Race_Data and Races. I have the following associations. Runners have_many Race_Data Races have_many Race_Data I also want create the association Runners Have_Many Races Through Race_Data, but as my look at the diagram I have drawn, there is already a many to one relationship from Race_data to Races. Does the combination of Runners having many Race_Data and Race_Data having one Race imply a Many_to_Many relationship between Runners and Races?

    Read the article

  • ActiveRecord Associations Question

    - by Mutuelinvestor
    I'm new to rails and have volunteered to help out the local High School Track team with a simple database that tracks the runners performances. For the moment, I have three models: Runners, Race_Data and Races. I have the following associations. Runners have_many Race_Data Races have_many Race_Data I also want create the association Runners Have_Many Races Through Race_Data, but as my look at the diagram I have drawn, there is already a many to one relationship from Race_data to Races. Does the combination of Runners having many Race_Data and Race_Data having one Race imply a Many_to_Many relationship between Runners and Races?

    Read the article

  • Including associations optimization in Rails

    - by Vitaly
    Hey, I'm looking for help with Ruby optimization regarding loading of associations on demand. This is simplified example. I have 3 models: Post, Comment, User. References are: Post has many comments and Comment has reference to User (:author). Now when I go to the post page, I expect to see post body + all comments (and their respective authors names). This requires following 2 queries: select * from Post -- to get post data (1 row) select * from Comment inner join User -- to get comment + usernames (N rows) In the code I have: Post.find(params[:id], :include => { :comments => [:author] } But it doesn't work as expected: as I see in the back end, there're still N+1 hits (some of them are cached though). How can I optimize that?

    Read the article

  • Passing two variables to separate table...associations problem

    - by bgadoci
    I have developed an application and I seem to be having some problems with my associations. I have the following: class User < ActiveRecord::Base acts_as_authentic has_many :questions, :dependent => :destroy has_many :sites , :dependent => :destroy end Questions class Question < ActiveRecord::Base has_many :sites, :dependent => :destroy has_many :notes, :through => :sites belongs_to :user end Sites (think of this as answers to questions) class Site < ActiveRecord::Base acts_as_voteable :vote_counter => true belongs_to :question belongs_to :user has_many :notes, :dependent => :destroy has_many :likes, :dependent => :destroy has_attached_file :photo, :styles => { :small => "250x250>" } validates_presence_of :name, :description end When a Site (answer) is created I am successfully passing the question_id to the Sites table but I can't figure out how to also pass the user_id. Here is my SitesController#create def create @question = Question.find(params[:question_id]) @site = @question.sites.create!(params[:site]) respond_to do |format| format.html { redirect_to(@question) } format.js end end

    Read the article

  • Ruby on Rails ActiveRecord/Include/Associations can't get my query to work

    - by Cypher
    I just started learning Rails and I'm just trying to set up query via associations. All the queries I try to write seem to be doing bizzare things and end up trying to query two tables parsed together with an '_' as one table. I have no clue why this would ever happen My tables are as follows: schools: id name variables: id name type var_entries: id variable_id entry school_entries: id school_id var_entry_id my rails association tables are $local = { :adapter => "mysql", :host => "localhost", :port => "3306".to_i, :database => "spy_2", :username =>"root", :password => "vertrigo" } class School < ActiveRecord::Base establish_connection $local has_many :school_entries has_many :var_entries, :through => school_entries end class Variable < ActiveRecord::Base establish_connection $local has_many :var_entries has_many :school_entries, :through => :var_entries end class VarEntry < ActiveRecord::Base establish_connection $local has_many_and_belongs_to :school_entries belongs_to :variables end class SchoolEntry < ActiveRecord::Base establish_connection $local belongs_to :school has_many :var_entries end I want to do this sql query: SELECT school_id, variable_id,rank FROM school_entries, variables, var_entries, schools WHERE var_entries.variable_id = variables.id AND school_entries.var_entry_id = var_entries.id AND schools.id = school_entries.school_id AND variables.type = 'number'; and put it into Rails notation: here is one of my many failed attempts schools = VarEntry.all(:include => [:school_entries, :variables], :conditions => "variables.type = 'number'") the error: 'const_missing': uninitialized constant VarEntry::Variables (NameError) if i remove variables schools = VarEntry.all(:include => [:school_entries, :variables], :conditions => "type = 'number'") the error is: Mysql::Error: Unkown column 'type' in 'where clause': SELECT * FROM 'var_entries' WHERE (type=number) (ActiveRecord::StatementInvalid) Can anyone tell me where I'm going horribly wrong?

    Read the article

  • Ruby on Rails Associations

    - by Eef
    Hey all, I am starting to create my sites in Ruby on Rails these days instead of PHP. I have picked up the language easily but still not 100% confident with associations :) I have this situation: User Model has_and_belongs_to_many :roles Roles Model has_and_belongs_to_many :users Journal Model has_and_belongs_to_many :roles So I have a roles_users table and a journals_roles table I can access the user roles like so: user = User.find(1) User.roles This gives me the roles assigned to the user, I can then access the journal model like so: journals = user.roles.first.journals This gets me the journals associated with the user based on the roles. I want to be able to access the journals like so user.journals In my user model I have tried this: def journals self.roles.collect { |role| role.journals }.flatten end This gets me the journals in a flatten array but unfortunately I am unable to access anything associated with journals in this case, e.g in the journals model it has: has_many :items When I try to access user.journals.items it does not work as it is a flatten array which I am trying to access the has_many association. Is it possible to get the user.journals another way other than the way I have shown above with the collect method? Hope you guys understand what I mean, if not let me know and ill try to explain it better. Cheers Eef

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >