Search Results

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

Page 10/28 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • 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

  • Rails Association issue with NoMethodError in event_controller

    - by pmanning
    Kinda a noob trying to understand I think I need to define rsvps but not sure what to put... I'm trying to add a Join/Unjoin button to user created Events, similar to a Follow/Unfollow button for Users. NoMethodError in Events#show undefined method `model_name' for NilClass:Class in line #1 _unjoin.html.erb 1: <%= form_for(current_user.rsvps.find_by_joined_id(@event), 2: html: { method: :delete }) do |f| %> 3: <%= f.submit "Leave", class: "btn btn-large" %> 4: <% end %> events_controller.rb def show @event = Event.find(params[:id]) @user = current_user end Here's the models rsvp.rb class Rsvp < ActiveRecord::Base attr_accessible :joined_id belongs_to :joiner, class_name: "User" belongs_to :joined, class_name: "User" validates :joiner_id, presence: true validates :joined_id, presence: true end user.rb has_many :rsvps, foreign_key: "joiner_id", dependent: :destroy has_many :joined_events, through: :rsvps, source: :joined has_many :reverse_rsvps, foreign_key: "joined_id", class_name: "Rsvp", dependent: :destroy has_many :joiners, through: :reverse_rsvps, source: :joiner event.rb belongs_to :user has_many :rsvps, foreign_key: "joiner_id", dependent: :destroy has_many :joined_events, through: :rsvps, source: :joined has_many :reverse_rsvps, foreign_key: "joined_id", class_name: "Rsvp", dependent: :destroy has_many :joiners, through: :reverse_rsvps, source: :joiner

    Read the article

  • Change a finder method w/ parameters to an association

    - by Sai Emrys
    How do I turn this into a has_one association? (Possibly has_one + a named scope for size.) class User < ActiveRecord::Base has_many :assets, :foreign_key => 'creator_id' def avatar_asset size = :thumb # The LIKE is because it might be a .jpg, .png, or .gif. # More efficient methods that can handle that are OK. ;) self.assets.find :first, :conditions => ["thumbnail = '#{size}' and filename LIKE ?", self.login + "_#{size}.%"] end end EDIT: Cuing from AnalogHole on Freenode #rubyonrails, we can do this: has_many :assets, :foreign_key => 'creator_id' do def avatar size = :thumb find :first, :conditions => ["thumbnail = ? and filename LIKE ?", size.to_s, proxy_owner.login + "_#{size}.%"] end end ... which is fairly cool, and makes syntax a bit better at least. However, this still doesn't behave as well as I would like. Particularly, it doesn't allow for further nice find chaining (such that it doesn't execute this find until it's gotten all its conditions). More importantly, it doesn't allow for use in an :include. Ideally I want to do something like this: PostsController def show post = Post.get_cache(params[:id]) { Post.find(params[:id], :include => {:comments => {:users => {:avatar_asset => :thumb}} } ... end ... so that I can cache the assets together with the post. Or cache them at all, really - e.g. get_cache(user_id){User.find(user_id, :include => :avatar_assets)} would be a good first pass. This doesn't actually work (self == User), but is correct in spirit: has_many :avatar_assets, :foreign_key => 'creator_id', :class_name => 'Asset', :conditions => ["filename LIKE ?", self.login + "_%"] (Also posted on Refactor My Code.)

    Read the article

  • has_many relation doesn't seems right or logical, some thing like belongs_to_many looks right

    - by Vijendra
    My situation is like this. Company has many users and users may belongs to many companies. And current implementation is something like below. class Company has_many :employments has_many :users, :through = :employments end class Employment belongs_to :company belongs_to :user end class User has_many :employments has_many :companies, :through = :employments #This doesn't looks correct end User has many companies doesn't looks logically meaningful.It must be some thing like belongs_to_many companies. Do I need to use has_and_belongs_to_many? But that also will gives the same meaning. Can some one please suggest the right way for representing these relationships?

    Read the article

  • jpa join query on a subclass

    - by Brian
    I have the following relationships in JPA (hibernate). Object X has two subclasses, Y and Z. Object A has a manyToOne relationship to object X. (Note, this is a one-sided relationship so object X cannot see object A). Now, I want to get the max value of a column in object A, but only where the relationship is of a specific subtype, ie...Y. So, that equates to...get the max value of column1 in object A, across all instances of A where they have a relationship with Y. Is this possible? I'm a bit lost as how to query it. I was thinking of something like: String query = "SELECT MAX(a.columnName) FROM A a join a.x; Query query = super.entityManager.createQuery(query); query.execute(); However that doesn't take account of the subclass of X...so I'm a bit lost. Any help would be much appreciated.

    Read the article

  • Using build with a has_one association in rails.

    - by espinet
    This is a really noob question but im having trouble finding the answer, is there a way in rails to have 0 or 1 association? For example, I create a user with no objects, than later on create an object for that user. I tried using build with a 'has_one' association but that blew up... The only way I see this working is using 'has_many'. The user is suppose to only have at most one of these objects, is there any way to do this?

    Read the article

  • Question About Fk refrence in The Collection

    - by Ahmed
    Hi , i have 2 entities : ( person ) & (Address) with follwing mapping : <class name="Adress" table="Adress" lazy="false"> <id name="Id" column="Id"> <generator class="native" /> </id> <many-to-one name="Person" class="Person"> <column name="PersonId" /> </many-to-one> </class> <class name="Person" table="Person" lazy="false"> <id name="PersonId" column="PersonId"> <generator class="native" /> </id> <property name="Name" column="Name" type="String" not-null="true" /> <set name="Adresses" lazy="true" inverse="true" cascade="save-update"> <key> <column name="PersonId" /> </key> <one-to-many class="Adress" /> </set> </class> my propblem is that when i set Adrees.Person with new object of person ,The collection person.Adresses doesn't update itself . should i update every end role of the association to be updated in the two both? another thing : if i updated the Fk manually like this : Adress.PersonId it doesn't break or change association. does this is Nhibernte behavior ? thanks in advance , i am waiting for your experiencies

    Read the article

  • Size of assosiation in Hibernate criteria.

    - by trnl
    Hello guys. I've faced with a problem when querying with Hibernate Criteria in Grails. Take a look: def visitors = Client.withCriteria{ visits{ use ( TimeCategory ) {between('date',date,date+1.month-1)} } sizeGe("visits",params.from) sizeLe("visits",params.to) fetchMode("visits", FM.JOIN) }; I need only those clients, which has number of visits in month between from and to bounds. But now size* restrictions is being applied to all visits. So if client has one visit in this month, and visit in previous month. And if I set from=2, this client will be in result. But it should not be there. Any help is appreciated. Thanks, Vova.

    Read the article

  • Which type of Rails model association should I use in this situation?

    - by jstayton
    I have two models/tables in my Rails application: discussions and comments. Each discussion has_many comments, and each comment belongs_to a discussion. My discussions table also includes a first_comment_id column and last_comment_id column for convenience and speed. I want to be able to call discussion.last_comment for the last comment model, but the following (in my discussion model) isn't working to make this happen: has_one :first_comment, :class_name => "Comment" has_one :last_comment, :class_name => "Comment" When I call discussion.last_comment, the following SQL is run: SELECT * FROM `comments` WHERE (`comments`.discussion_id = 1) LIMIT 1 It's using the discussions.id column to join against comments.discussion_id, when I want it to join discussions.last_comment_id against comments.id. Am I using the wrong type of association here? Thanks for your help!

    Read the article

  • Get ID of the object saved with association

    - by Pravin
    Hi, Here is my scenario: I have three models Subscriber, Subscription, Plan, with has_many :through relationship between Subscriber and Plans. A subscriber can have multiple plans with one active plan. Whenever a subscriber selects a plan I save it using accepts_nested_attributes_for :subscriptions. I get one plan from the form. Now my problem is I want to get the ID of the record created in subscriptions table.

    Read the article

  • Newbie question attribute from associated table not showing up in index view

    - by Lauren
    Hi I know this is something simple I am doing wrong. I have three tables, installation, neighborhood, schools Installation: has_many :schools has_many :neighborhoods Neighborhood: has_many :installations has_many :schools Schools: belongs_to :installations belongs_to :neighborhoods I can't figure out how to show the name of the neighborhood the school is located in on the index view. I can get it to show on the show view once I have the school id. But on the index view I can't figure out what to put in the controller that will allow me to access the neighborhood name from the neighborhood_id that is in the School model. I am sure this is so easy and I am screwing up something stupid. HELP!

    Read the article

  • has_many relation doesn't seems right or logical in business perceptive, needed some thing like belo

    - by Vijendra
    My situation is like this. Company has many users and users may belongs to many companies. And current implementation is something like below. class Company has_many :employments has_many :users, :through = :employments end class Employment belongs_to :company belongs_to :user end class User has_many :employments has_many :companies, :through = :employments #This doesn't looks correct end It works, but "user has many companies" doesn't looks logically meaningful. It must be some thing like belongs_to_many companies. Do I need to use has_and_belongs_to_many? Can some one please suggest the right way for representing these relationships?

    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

  • inheriting scope from a has_many relationship

    - by hb922
    I am using ruby on rails 3.1 and have 2 models, an event and a group. Each event has_many groups, but has to have at least one "master" group, where the column :is_master = true Class Group < ActiveRecord::Base has_many :users belongs_to :event scope :master, where (:is_master => true) end Class Event< ActiveRecord::Base has_many :groups def master_group groups.master end end I want to be able to default all properties of the master group to the event, so for example, event.users.count should be the same as event.master_group.users.count. Is there any way to do something like this? Can I do a has_many :through = master_group? Am I approaching this the wrong way? Thanks!

    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

  • has_many :through name suggestions

    - by user1084769
    I have three models, user, achievement, badge and I plan on using has_many :through instead of has_many_and_belongs_to since I will have a few extra fields in the join tables. According to a Railscast I watched, using this method requires coming up with new model names and not user_badge or user_achievement. For my User Achievement join what do you think of Accomplishment? For my User Badge join what do you think of Distinction?

    Read the article

  • has_many conditions or proc on foreign key

    - by ere
    I have a has_many association between two models using a date as both the foreign and primary key for each model. It works perfectly one way but not the other. Works has_one :quiz_log, :primary_key => :start_at, :foreign_key => :start_at Doesn't work has_many :event_logs, :primary_key => :start_at, :foreign_key => :start_at The reason being (i think) because the start_at on QuizLog is a date and the start_at on EventLog is a datetime. So it returns nil trying to match the exact datetime on a simple date. How can I cast the foreign_key start_at on the second statement to convert it first from datetime to simply date so it will match the second model?

    Read the article

  • join same rails models twice, eg people has_many clubs through membership AND people has_many clubs through committee

    - by Ben
    Models: * Person * Club Relationships * Membership * Committee People should be able to join a club (Membership) People should be able to be on the board of a club (Committee) For my application these involve vastly different features, so I would prefer not to use a flag to set (is_board_member) or similar. I find myself wanting to write: People has_many :clubs :through = :membership # :as = :member? :foreign_key = :member_id? has_many :clubs :through = :committee # as (above) but I'm not really sure how to stitch this together

    Read the article

  • Double join with habtm in ActiveRecord

    - by Daniel Huckstep
    I have a weird situation involving the need of a double inner join. I have tried the query I need, I just don't know how to make rails do it. The Data Account (has_many :sites) Site (habtm :users, belongs_to :account) User (habtm :sites) Ignore that they are habtm or whatever, I can make them habtm or has_many :through. I want to be able to do @user.accounts or @account.users Then of course I should be able to do @user.accounts < @some_other_account And then have @user.sites include all the sites from @some_other_account. I've fiddled with habtm and has_many :through but can't get it to do what I want. Basically I need to end up with a query like this (copied from phpmyadmin. Tested and works): SELECT accounts.* FROM accounts INNER JOIN sites ON sites.account_id = accounts.id INNER JOIN user_sites ON sites.id = user_sites.site_id WHERE user_sites.user_id = 2 Can I do this? Is it even a good idea to have this double join? I am assuming it would work better if users had the association with accounts to begin with, and then worry about getting @user.sites instead, but it works better for many other things if it is kept the way it is (users <- sites).

    Read the article

  • UML binary association aggregatee has access to aggregator

    - by user314172
    Firstly, I'd like to thank those who answered my previous question ages ago. Currently I'm engaging more in the design phase UMLs, as this is my first medium scale deployment I'm entrusted with. This is extremely simple, but it bugs me so. If (Component) owns (Manager of Component), and (Manager of Component) has a reference to (Component) through which it manages it; how do you fully describe the relationship? I know it is aggregative, but how do you describe (Manager of Component) possessing a reference/pointer to the (Component) that physically owns the (Manager of Component) ? Example: Lidar owns a LidarManager

    Read the article

  • Analyze big human database

    - by Neir0
    Lets we have a big people database. Each human has a many parameters: age, weight, favorite music, favorite films, education etc. I want to know how one feature associate with other features. For example, if human has a good education what it means for musical preferences? Or how films preferences changes with age? I know about assotian rules algorithms like apriory but i donnt want just to found assotiation rules, i want to know how one specific feature affect to others. Which keywords i must to use for google?

    Read the article

  • How to use jQuery to generate 2 new associated objects in a nested form?

    - by mind.blank
    I have a model called Pair, which has_many :questions, and each Question has_one :answer. I've been following this railscast on creating nested forms, however I want to generate both a Question field and it's Answer field when clicking on an "Add Question" link. After following the railscast this is what I have: ..javascripts/common.js.coffee: window.remove_fields = (link)-> $(link).closest(".question_remove").remove() window.add_fields = (link, association, content)-> new_id = new Date().getTime() regexp = new RegExp("new_" + association, "g") $(link).before(content.replace(regexp, new_id)) application_helper.rb: def link_to_add_fields(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.simple_fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, "window.add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")", class: "btn btn-inverse") end views/pairs/_form.html.erb: <%= simple_form_for(@pair) do |f| %> <div class="row"> <div class="well span4"> <%= f.input :sys_heading, label: "System Heading", placeholder: "required", input_html: { class: "span4" } %> <%= f.input :heading, label: "User Heading", input_html: { class: "span4" } %> <%= f.input :instructions, as: :text, input_html: { class: "span4 input_text" } %> </div> </div> <%= f.simple_fields_for :questions do |builder| %> <%= render 'question_fields', f: builder %> <% end %> <%= link_to_add_fields "<i class='icon-plus icon-white'></i> Add Another Question".html_safe, f, :questions %> <%= f.button :submit, "Save Pair", class: "btn btn-success" %> <% end %> _question_fields.html.erb partial: <div class="question_remove"> <div class="row"> <div class="well span4"> <%= f.input :text, label: "Question", input_html: { class: "span4" }, placeholder: "your question...?" %> <%= f.simple_fields_for :answer do |builder| %> <%= render 'answer_fields', f: builder %> <% end %> </div> </div> </div> _answer_fields.html.erb partial: <%= f.input :text, label: "Answer", input_html: { class: "span4" }, placeholder: "your answer" %> <%= link_to_function "remove", "remove_fields(this)", class: "float-right" %> I'm especially confused by the reflect_on_association part, for example how does calling .new there create an association? I usually need to use .build Also for a has_one I use .build_answer rather than answers.build - so what does this mean for the jQuery part?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >