belongs_to through associations

can someone help me look at this. Getting too tired.

class User has_many :questions has_many :choices end class Question belongs_to :user has_many :answers has_one :choice, :through => :answer end class Answer belongs_to :question end class Choice belongs_to :user belongs_to :answer belongs_to :question, :through => :answer validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ] end

I am getting a NameError uninitialized constant User::Choice when I try to do current_user.choices

It works fine, if I don't include the

belongs_to :question, :through => :answer

But I want to use that because I want to be able to do the validates_uniqueness_of

I am probably overlooking something simple. Any help would be appreciated. Thanks!

-------------Problems Reply------------

A belongs_to association cannot have a :through option. You're better off caching the question_id on Choice and adding a unique index to the table (especially because validates_uniqueness_of is prone to race conditions).

If you're paranoid, add a custom validation to Choice that confirms that the answer's question_id matches, but it sounds like the end user should never be given the opportunity to submit data that would create this kind of mismatch.

You can also delegate:

class Company < ActiveRecord::Base
has_many :employees
has_many :dogs, :through => :employees

class Employee < ActiveRescord::Base
belongs_to :company
has_many :dogs

class Dog < ActiveRecord::Base
belongs_to :employee

delegate :company, :to => :employee, :allow_nil => true

Just use has_one instead of belongs_to in your :though, like this:

class Choice
belongs_to :user
belongs_to :answer
has_one :question, :through => :answer

Unrelated, but I'd be hesitant to use validates_uniqueness_of instead of using a proper unique constraint in your database. When you do this in ruby you have race conditions.

My approach was to make a virtual attribute instead of adding database columns.

class Choice
belongs_to :user
belongs_to :answer

# ------- Helpers -------
def question

# extra sugar
def question_id

This approach is pretty simple, but comes with tradeoffs. It requires Rails to load answer from the db, and then question. This can be optimized later by eager loading the associations you need (i.e. c = Choice.first(include: {answer: :question})), however, if this optimization is necessary, then stephencelis' answer is probably a better performance decision.

There's a time and place for certain choices, and I think this choice is better when prototyping. I wouldn't use it for production code unless I knew it was for an infrequent use case.

You could simply use has_one in place of belongs_to :

has_one :question, :through => :answer

It sounds like what you want is a User who has many Questions.
The Question has many Answers, one of which is the User's Choice.

Is this what you are after?

I would model something like that along these lines:

class User
has_many :questions

class Question
belongs_to :user
has_many :answers
has_one :choice, :class_name => "Answer"

validates_inclusion_of :choice, :in => lambda { answers }

class Answer
belongs_to :question

The has_many :choices creates an association named choices, not choice. Try using current_user.choices instead.

See the ActiveRecord::Associations documentation for information about about the has_many magic.

Category:activerecord Views:0 Time:2010-10-26

Related post

  • what would happen if you use belongs_to without having a corresponding has_one? 2009-03-30

    I have a core model for an Item, and a script to populate it from a custom source (think, RSS feed). In the feed, each Item is identified with a guid; in my system, Item only has an autogenerated id primary key. I want to have, let's say, ItemFeedInf

  • has_one on a belongs_to in Rails? 2009-05-07

    I am building a rails site and am having trouble with the associations. Basically I have the following: class Publication < ActiveRecord::Base belongs_to :category has_one :site, :through => :category named_scope :on_site, lambda {|s| {:include

  • Difference between has_one and belongs_to in Rails? 2009-05-14

    This question already has an answer here: What's the difference between belongs_to and has_one? 2 answers I am trying to understand has_one relationship in RoR. Let's say I have two models - Person and Cell: class Person < ActiveRecord::Base has_o

  • Group_by on a belongs_to assocciation 2009-05-21

    I would like to use the group_by method, but instead of using a column in the database: @posts.group_by(&:date) I want to have something like: @posts.group_by(&:author) Where post belongs_to author. I'm just not sure of the syntax? ----------

  • Rails: belongs_to vs has_one 2009-05-22

    A bit of a newbie question on rails associations. I have a Bug model, and a Status model. Status is basically just a key/value pair table. Out of the choices available, I would say Bug has_one Status makes the most sense. However, according to this C

  • Does has_many require belongs_to on the other side? 2009-05-28

    If Parent has_many :children, must Child :belongs_to :parent? --------------Solutions------------- No, the belongs_to isnt necessary. It will mean that you wont be able to query the association from both directions, but if that is not a requirement f

  • How to specify join conditions in Rails for belongs_to assocation? 2009-07-26

    I'm trying to create an association between two models using join conditions rather than a foreign key. Does anyone know if this is possible? For example I want to join products to pricing points. A product has a price and a pricing point has a minim

  • Using ActiveRecord belongs_to with two keys 2009-07-29

    I have two ActiveRecord models with a hasMany / belongsTo association: class User < ActiveRecord::Base has_many :letters end class Letter < ActiveRecord::Base belongs_to :user end The User model has a revision_number attribute, to which I would

  • belongs_to not using primary key option 2009-08-01

    I've been struggling with this for a while, and decided to throw it out there: I have 3 models, User, Connection, Suspect A User has many Connections, A Connection has one Suspect, linked via case_id A User has many Suspects through its Connections.

  • Getting fields_for and accepts_nested_attributes_for to work with a belongs_to relationship 2009-08-21

    I cannot seem to get a nested form to generate in a rails view for a belongs_to relationship using the new accepts_nested_attributes_for facility of Rails 2.3. I did check out many of the resources available and it looks like my code should be workin

  • belongs_to association query method doesn't exist 2009-08-25

    The "association?" query method that the Rails docs say should exist when I create a belongs_to association doesn't actually get created: class Author < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :author e

  • Accessing a belongs_to associated model via has_one :through 2009-09-04

    I can't seem to figure out why this association isn't working: I'm not sure how to describe the situation better than providing a code example: Here is my application environment: Ruby version 1.8.7 (universal-darwin10.0) Rails version 2.3.3 And a co

  • Rails: order using a has_many/belongs_to relationship 2009-10-07

    I was wondering if it was possible to use the find method to order the results based on a class's has_many relationship with another class. e.g. # has the columns id, name class Dog < ActiveRecord::Base has_many :dog_tags end # has the columns id,

  • How to disable default_scope for a belongs_to? 2009-10-08

    Is there a way to disable the default_scope for a single belongs_to association? The default_scope is fine for all but a single belongs_to that I would like to bypass the scope. I'm familiar with with_exclusive_scope however I don't think that can be

  • Removing the :has_many when the :belongs_to is updated/destroyed if the :has_many is now empty 2009-10-09

    I have states who have many cities (belongs_to :state) who have many businesses (belongs_to :city). State also… has_many :businesses, :through => :cities On my site everything is managed from the Business perspective. When a new Business is create

  • Ruby on Rails: Nested Attributes, belongs_to relation 2009-10-20

    I hope you can help me. I have a User entity that has a Current Location field (city and country). To old this info I created an entity called Location which has_many Users. I'm not entirely sure if I should put in the User model "has_one" or "belong

  • Can a model "belongs_to" either/or more than one model? 2009-11-09

    Apologies if this is a slightly noob question, but looking to clarify my thoughts on this. I have a model that can EITHER belong to one model, or another. For example: Let's say I have a Team model and I have a Member model, and both of those models

  • order products by association count belongs_to 2009-11-19

    Class Sale belongs_to :product, :accessible => true belongs_to :brand, :accessible => true end Class Product has_many :sales belongs_to :brand end Class Brands has_many :products has_many :sales end How do i get the brands that have the most pr

  • Rails: save a record via belongs_to and setting the foreign key 2009-11-19

    Is there a better way of writing this code? It just doesn't sit right with me, I feel like there is something really 'rails like' that I should already know: belongs_to :parent_in_use belongs_to :parent_template def after_create new_parent_in_use = P

  • Has_many/belongs_to association not saving due to polymorphic associations? 2009-12-02

    I'm trying to create a log of attributes that have changed within each update to a certain message. The attributes are IssueStatus and IssueType, and both have two polymorphic associations with UpdateAction, that saves the changed_from_id and changed

Copyright (C), All Rights Reserved.

processed in 0.115 (s). 11 q(s)