Search Results

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

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

  • rails override default getter for a relationship (belongs_to)

    - by brad
    So I know how to override the default getters for attributes of an ActiveRecord object using def custom_getter return self[:custom_getter] || some_default_value end I'm trying to achieve the same thing however for a belongs to association. For instance. class Foo < AR belongs_to :bar def bar return self[:bar] || Bar.last end end class Bar < AR has_one :foo end When I say: f = Foo.last I'd like to have the method f.bar return the last Bar, rather than nil if that association doesn't exist yet. This doesn't work however. The reason is that self[:bar] is always undefined. It's actually self[:bar_id]. I can do something naive like: def bar if self[:bar_id] return Bar.find(self[:bar_id]) else return Bar.last end end However this will always make a db call, even if Bar has already been fetched, which is certainly not ideal. Does anyone have an insight as to how I might have a relationship such that the belongs_to attribute is only loaded once and has a default value if not set.

    Read the article

  • Doctrine2 update both sides of association

    - by orourkedd
    I'm using this to update both sides of an association but want to know if there is a more efficient way to do this. In this case, it is a self-referencing OneToMany parent/child association: public function setParent(Node $parent, $inverse = true) { $this->parent = $parent; if($inverse) $parent->addChild($this, false); } public function addChild(Node $child, $inverse = true) { if(!$this->children->contains($child)) { $this->children[] = $child; if($inverse) $child->setParent($this, false); } }

    Read the article

  • ActiveScaffold complains about association

    - by Bilal Aslam
    I'm using ActiveScaffold to create an Admin UI. I have two models: Post and Comments. A Post has-many Comments, and a Comment belongs-to a post. There's a validates_presences_of :text validation the Comment model. The problem is that when I create a new Post from the Admin UI without creating a new Comment in the subform, ActiveScaffold complains about the validation. I can create the Post if I also create a Comment associated with it, which is not what I Want. I can create a new Post manually from script/console. What gives?

    Read the article

  • [PHP] Associate different data

    - by Alex Cane
    I will try to be as clear as possible because I can't get anybody to help me around, I am trying to associate some data from a 'videos' table with their respective ID. Lets say, I have column ID, title, serie, season, episode. I am getting my data : <? $result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'"); $total_rows = mysql_num_rows($result); ?> (that is in the page where you see the video itself) So now I can get the number of episodes from a serie and season. What I'm trying to do is have a link for the next episode, and aa link for the previous one. In the URL I am working with the id, so http://website.com/view/id/'video id here'/ So how can I get the ID of the following and previous episodes of the same season AND serie? Help will be much appreciated! The easiest thing I thought of is <?=$row['id'] + 1?> <?=$row['id'] - 1?> But the thing is that it's mixed videos, so it wont work 100%

    Read the article

  • Complicted ActiveRecord Association. Going through a 4th table

    - by Dex
    I have kind of a complicated case and am wondering how this would work in rails: I want to categories the genres of some singers. Singers can belong to more than one genres, and users can assign tags to each genre For example: singers <-- singers_genres -- genres <-- genres_tags -- tags SQL would look something like: SELECT * FROM singers S INNER JOIN singers_genres SG ON S.id=SG.singer_id INNER JOIN genres G ON G.id = SG.genre_id LEFT OUTER JOIN genre_tags GT ON G.id = GT.genre_id INNER JOIN tags T ON GT.tag_id = T.id

    Read the article

  • AssociatedControlId of inner namingcontainer

    - by Eric
    Hi, I have a custom control contains a label control. I want to set the AssociatedControlId of this label to be other control id on the page, but as soon as I implement the INamingContainer in my custom control, it will run into an error saying "Unable to find control with id 'abc' that is associated with the Label 'xyz'." This would be due to the fact that the label is in a nested naming container and it trys to find the control within the same container but couldn't (as the control is on the page, outside of it own naming container) Anyone know of a way to set this property? Thanks, Eric

    Read the article

  • Associated models in Rails?

    - by dannymcc
    Hi Everyone, In my rails application I have two models called Kases and Notes. They work in the same way comments do with blog posts, I.e. each Kase entry can have multiple notes attached to it. I have got everything working, but for some reason I cannot get the destroy link to work for the Notes. I think I am overlooking something that is different with associated models to standard models. Notes Controller class NotesController < ApplicationController # POST /notes # POST /notes.xml def create @kase = Kase.find(params[:kase_id]) @note = @kase.notes.create!(params[:note]) respond_to do |format| format.html { redirect_to @kase } format.js end end end Kase Model class Kase < ActiveRecord::Base validates_presence_of :jobno has_many :notes Note Model class Note < ActiveRecord::Base belongs_to :kase end In the Kase show view I call a partial within /notes called _notes.html.erb: Kase Show View <div id="notes"> <h2>Notes</h2> <%= render :partial => @kase.notes %> <% form_for [@kase, Note.new] do |f| %> <p> <h3>Add a new note</h3> <%= f.text_field :body %><%= f.submit "Add Note" %> </p> <% end %> </div> /notes/_note.html.erb <% div_for note do %> <div id="sub-notes"> <p> <%= h(note.body) %><br /> <span style="font-size:smaller">Created <%= time_ago_in_words(note.created_at) %> ago on <%= note.created_at %></span> </p> <%= link_to "Remove Note", kase_path(@kase), :confirm => 'Are you sure?', :method => :delete, :class => 'important' %> </div> <% end %> As you can see, I have a Remove Note destroy link, but that destroys the entire Kase the note is associated with. How do I make the destroy link remove only the note? <%= link_to "Remove Note", kase_path(@kase), :confirm => 'Are you sure?', :method => :delete, :class => 'important' %> Any help would, as always, be greatly appreciated! Thanks, Danny

    Read the article

  • Rails migration: t.references with alternative name?

    - by marienbad
    So I have a create_table like this for Courses at a School: create_table :courses do |t| t.string :name t.references :course t.timestamps end but I want it to reference TWO other courses like: has_many :transferrable_as #a Course has_many :same_as #another Course can I say t.references :transferrable_as, :as= :course ?

    Read the article

  • Rails / ActiveRecord Modeling Help

    - by JM
    I’m trying to model a relationship in ActiveRecord and I think it’s a little beyond my skill level. Here’s the background. This is a horse racing project and I’m trying to model a horses Connections over time. Connections are defined as the Horse’s Current: Owner, Trainer and Jockey. Over time, a horse’s connections can change for a lot of different reasons: The owner sells the horse in a private sale The horse is claimed (purchase in a public sale) The Trainer switches jockeys The owner switches trainers In my first attempt at modeling this, I created the following tables: Horses, Owners, Trainers, Jockeys and Connections. Essentially, the Connections table was the has-many-through join table and was structured as follows: Connections Table 1 Id Horse_id Owner_id Trainer_id Jockey_id Status_Code Status_Date Change_Code The Horse, Owner, Trainer and Jockey foreign keys are self explanatory. The status code is 1 or 0 (1 active, 0 inactive) and the status date is the date the status changed. Change_code is and integer or string value that represent the reason for the change (private sale, claim, jockey change, etc) The key benefit of this approach is that the Connection is represented as one record in the connections table. The downside is that I have to have a table for Owner (1), Trainer (2) and Jockey (3) when one table could due. In my second attempt at modeling this I created the following tables: Horses, Connections, Entities The Entities tables has the following structure Entities Table id First_name Last_name Role where Role represents if the entity is a Owner, Trainer or Jockey. Under this approach, my Connections table has the following structure Connections Table 2 id Horse_id Entity_id Role Status_Code Status_Date Change_Code 1 1 1 1 1 1/1/2010 2 1 4 2 1 1/1/2010 3 1 10 3 1 1/1/2010 This approach has the benefit of eliminating two tables, but on the other hand the Connection is now comprised of three different records as opposed to one in the first approach. What believe I’m looking for is an approach that allows me to capture the Connection in one record, but also uses an Entities table with roles instead of the Owner, Trainer and Jockey tables. I’m new to ActiveRecord and rails so any and all input would be greatly appreciated. Perhaps there are other ways that would even be better. Thanks!

    Read the article

  • Rails Association Question (addendum)...

    - by keruilin
    My original question and accepted solution was posted here: http://stackoverflow.com/questions/2483640/rails-association-question. Check that out first. My follow-up question is this: I want to return an object that has both the user attributes and the race attributes. That way I can access, for example, the user's name and the fastest_time. How can this be accomplished? I've tried several approaches, but none I've been satisfied with.

    Read the article

  • Association and model data saving problem

    - by Zhlobopotam
    Developing with cakephp 1.3 (latest from github). There are 2 models bind with hasAndBelongsToMany: documents and tags. Document can have many tags in other words. I've add a new document submitting form there user can enter a list of tags separated with commas (new tag will be added, if not exist already). I looked at cakephp bakery 2.0 source code on github and found the solution. But it seems that something is wrong. class Document extends AppModel { public $hasAndBelongsToMany = array('Tag'); public function beforeSave($options = array()) { if (isset($this->data[$this->alias]['tags']) && !empty($this- >data[$this->alias]['tags'])) { $tagIds = $this->Tag->saveDocTags($this->data[$this->alias] ['tags']); unset($this->data[$this->alias]['tags']); $this->data[$this->Tag->alias][$this->Tag->alias] = $tagIds; } return true; } } class Tag extends AppModel { public $hasAndBelongsToMany = array ('Document'); public function saveDocTags($commalist = '') { if ($commalist == '') return null; $tags = explode(',',$commalist); if (empty($tags)) return null; $existing = $this->find('all', array( 'conditions' => array('title' => $tags) )); $return = Set::extract($existing,'/Tag/id'); if (sizeof($existing) == sizeof($tags)) { return $return; } $existing = Set::extract($existing,'/Tag/title'); foreach ($tags as $tag) { if (!in_array($tag, $existing)) { $this->create(array('title' => $tag)); $this->save(); $return[] = $this->id; } } return $return; } } So, new tags creation works well but document model can't save association data and tells: SQL Error: 1054: Unknown column 'Array' in 'field list' Query: INSERT INTO documents (title, content, shortnfo, date, status) VALUES ('Document with tags', '', '', Array, 1) Any ideas how to solve this problem?

    Read the article

  • why is this rails association loading individually after an eager load?

    - by codeman73
    I'm trying to avoid the N+1 queries problem with eager loading, but it's not working. The associated models are still being loaded individually. Here are the relevant ActiveRecords and their relationships: class Player < ActiveRecord::Base has_one :tableau end Class Tableau < ActiveRecord::Base belongs_to :player has_many :tableau_cards has_many :deck_cards, :through => :tableau_cards end Class TableauCard < ActiveRecord::Base belongs_to :tableau belongs_to :deck_card, :include => :card end class DeckCard < ActiveRecord::Base belongs_to :card has_many :tableaus, :through => :tableau_cards end class Card < ActiveRecord::Base has_many :deck_cards end and the query I'm using is inside this method of Player: def tableau_contains(card_id) self.tableau.tableau_cards = TableauCard.find :all, :include => [ {:deck_card => (:card)}], :conditions => ['tableau_cards.tableau_id = ?', self.tableau.id] contains = false for tableau_card in self.tableau.tableau_cards # my logic here, looking at attributes of the Card model, with # tableau_card.deck_card.card; # individual loads of related Card models related to tableau_card are done here end return contains end Does it have to do with scope? This tableau_contains method is down a few method calls in a larger loop, where I originally tried doing the eager loading because there are several places where these same objects are looped through and examined. Then I eventually tried the code as it is above, with the load just before the loop, and I'm still seeing the individual SELECT queries for Card inside the tableau_cards loop in the log. I can see the eager-loading query with the IN clause just before the tableau_cards loop as well. EDIT: additional info below with the larger, outer loop Here's the larger loop. It is inside an observer on after_save def after_save(pa) @game = Game.find(turn.game_id, :include => :goals) @game.players = Player.find :all, :include => [ {:tableau => (:tableau_cards)}, :player_goals ], :conditions => ['players.game_id =?', @game.id] for player in @game.players player.tableau.tableau_cards = TableauCard.find :all, :include => [ {:deck_card => (:card)}], :conditions => ['tableau_cards.tableau_id = ?', player.tableau.id] if(player.tableau_contains(card)) ... end end end

    Read the article

  • rails Creating a model instance automatically when another is created

    - by bob
    Hello I have a user model and a ratings model. Whenever a new user is created I want to create a new feedback model with it automatically. Each user model has one feedback model and each feedback model has many ratings. My Classes class User < ActiveRecord::Base end class Feedback < ActiveRecord::Base belongs_to :user has_many :ratings end class Rating < ActiveRecord::Base belongs_to :feedback end My database tables -user doesn't have anything special -feedback has user_id. This user_id should be the same as the user that has just been created. For example, user_id of 1 is created, then a feedback model should be created that belongs to user_id of 1. So the user_id column in the feedback database will also be 1. - Rating has a feedback_id and a user_id the user_id in this case is the id of the person who submitted the rating. I am having it assigned through the build command. I believe my process is correct here. The Goal The goal is to have each user have a feedback table that has many ratings from other users. So if someone goes to the feedback page, they will see all the ratings given and by who. Is there a better way to approach this? How do you create a model of feedback with the same id as the user being created right when a new user is created. The idea is that when a user is created a feedback is created associated with that user so people can then go to http://localhost:3000/users/1/feedback/ and submit new ratings. I'm trying to bypass having a user rate another user with just a ratings model because I'm not sure how to do it.

    Read the article

  • In Rails, how can a record belong_to a single user, but also have multiple "secondary" users?

    - by Kuro
    In my app, I have a User model and a Project model. A user has_many assignments and each project belongs_to a user. But along with each project having an owner, the user who created it, I would like the owner be able to share it with others (so that the project gets shown on the other users' account along with their own). I imagine having to use has_many :through, and setting up a projects_users table with a user_id and a project_id. And I guess this would be the end result? Project.first.user # The creator of the project => #<User id: 1, name: 'andrew', etc...> Project.first.users # The users that the creator chose to share it with => [#<User id: 2 ...>, #<User id: 3 ...>] How would I go about doing this? Thanks!

    Read the article

  • How to get visual studio 10 to open .mk files in the same instance?

    - by Russ Schultz
    I've recently been migrated to windows 7, and upon re-installing VS2010, it seems to want to treat .mk files differently than it used to. For whatever reason, it insists on opening a new instance of visual studio to edit these files. It doesn't for .c, .h, etc. I've tried using types, a freeware association manager, to change how it is associated. I've deleted the association, recreated, etc. but it still seems to want to treat these separately. Anybody know how to beat this thing into submission?

    Read the article

  • Rails :dependent => :destroy VS :dependent => :delete_all

    - by Sergey
    In rails guides it's described like this: "Objects will be in addition destroyed if they’re associated with :dependent = :destroy, and deleted if they’re associated with :dependent = :delete_all." Right, cool. But what's the difference between being destroyed and being deleted? I tried both and it seems to do the same thing.

    Read the article

  • How can I use Hibernate Criteria's to query nested tables?

    - by cbmeeks
    I've looked all over SO and Google but I guess I'm not using the right search terms or something. Anyway, say I have three tables: Companies ----------------------------------------- id name user_id Users ----------------------------------------- id username usertype_id UserTypes ----------------------------------------- id typeofuser So ACME would be a company, it would have a user Moe and Moe would be a usertype of Stooge. In SQL, I would do something like: select * from companies c join users u on (u.id = c.user_id) join usertypes ut on (ut.id = u.usertype_id) where ut.typeofuser = 'Stooge' But I can't seem to figure out how to do that in a Criteria. I have tried: Criteria crit = io.getSession().createCriteria(Company.class); List<Company> list = crit.createCriteria("users") .createCriteria("usertypes") .add(Restriction.eq("typeofuser", "Stooge").list(); But I get back way too many records. And the results don't even come close to being accurate. I've also tried: Criteria crit = io.getSession().createCriteria(Company.class); List<Company> list = crit.createAlias("users", "u") .createAlias("u.usertypes", "ut") .add(Restriction.eq("ut.typeofuser", "Stooge").list(); Seems to bring back the exact same result set. I actually have read the user manual. And when I nest only one level deep (ie, searching by users is fine) but when I get two layers deep, I can't quite get it. And the manual is no help. I just can't relate cats and kittens to business objects. Maybe they should use cats, kittens and fleas? :-/ Thanks for any suggestions.

    Read the article

  • How extensive is an Object in CakePHP model linkage?

    - by Andre
    I was hoping someone with an understanding on CakePHP could shed some light on a question I've been having. Here's my scenario, I have a User this User has a Company which in turn has many Department and many Address. If I were to get a User could I expect to have access to the Company and all models associated with that Company? So would $user['Company']['Department'][0] or $user['Company']['Address'][0] be possible? Which brings me back to the original question, how extensive is the linkage between models?

    Read the article

  • Django: way to test what class a generic relation content_object is?

    - by bitbutter
    In my project I have a class, NewsItem. Instances of NewsItem act like a wrapper. They can be associated with either an ArtWork instance, or an Announcement instance. Here's how the NewsItem model looks: class NewsItem(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') date = models.DateTimeField(default=datetime.datetime.now,) class Meta: ordering = ('-date',) def __unicode__(self): return (self.title()) In a template I'm dealing with a NewsItem instance, and would like to output a certain bunch of html it it's 'wrapping' an Artwork instance, and a different bunch of html if it's wrapping an Announcement instance. Could someone explain how I can write a conditional to test for this? My first naive try looked like this: {% if news_item.content_object.type=='Artwork' %}do this{% else %}do that{% endif %}

    Read the article

  • How to do HABTM management with auto completion in Rails?

    - by Andrei
    I am looking for a good solution for a probably typical problem of managing models with HABTM association in Rails. Let's assume that we have two models -- products and categories: Products has_many :categorizations has_many :categories, :through => :categorizations Categories has_many :categorizations has_many :products, :through => :categorizations Categorization belongs_to :product belongs_to :category Pat Shaughnessy is developing modified auto_complete plugin which can allow to manage one-to-many (and many-to-many) association: For someone that would be enough, but I don't really like so many text fields. I guess it is possible to combine the Ryan Bates' screencasts used by Pat in a slightly different way, namely, using one text field with autocomplete: Also it would be better to remove from the list of suggested tasks (one-to-many), or products|categories (many-to-many) those which have been already added. In the case of products-categories relationship, such auto completion would be used both in the form for product, and in the form for category. I hope that there is an existing plugin for that. I am not very experienced in Ruby, and don't really know how to implement such logic by myself. Any help is appreciated!

    Read the article

  • has_one update problem

    - by Kalyan M
    I have two models, User and Account. Each user may have one account. Creating an account for a user works fine. My problem is that when I try to update the account, the previous accounts user_id is nullified and a new account row is created with the user_id. I do not want this happening. I want to update the existing row with the changes to account. How do I do this? Thanks.

    Read the article

  • Suggestions on how to track tag count for a particular object

    - by Robin Fisher
    Hi, I'm looking for suggestions on how to track the number of tags associated with a particular object in Rails. I'm using acts_as_taggable_on and it's working fine. What I would like to be able to do is search for all objects that have no tags, preferably through a scope i.e. Object.untagged.all My first thought was to use an after_save callback to update an attribute called "taggings_count" in my model: def update_taggings_count self.taggings_count = self.tag_list.size self.save end Unfortunately, this does the obvious thing of putting me in an infinite loop. I need to use an after_save callback because the tag_list is not updated until the main object is saved. Would appreciate any suggestions as I'm on the verge of rolling my own tagging system. Regards Robin

    Read the article

  • Rails Association Problem

    - by looloobs
    I am having trouble with this association. I need to get an array of the primaries that belong to the soldiers in a platoon. So once I get all the soldiers in a platoon: @company = Company.find_by_id(1) @platoons = @company.platoons <% @platoons.each do |p| %> <%= p.soldiers.primaries.find(:all,:conditions => ["relationship = ? AND contacted = ?", 'Spouse', 'Yes'])) %> <% end %> * So there is no method for primaries, I assume this is because I am trying to call an association on an array. Soldiers have a platoon_id but primaries do not, they only have the association to soldiers in that platoon. How do I do this? I need it to return an array of Primaries. Thanks in advance! class Soldier < ActiveRecord::Base belongs_to :company belongs_to :platoon has_many :primaries, :dependent => :destroy end class Platoon < ActiveRecord::Base belongs_to :company belongs_to :battalion has_many :soldiers end class Primary < ActiveRecord::Base belongs_to :soldier belongs_to :company end

    Read the article

  • Ruby on Rails updating join table records

    - by Eef
    Hey, I have two models Users and Roles. I have setup a many to many relationship between the two models and I have a joint table called roles_users. I have a form on a page with a list of roles which the user checks a checkbox and it posts to the controller which then updates the roles_users table. At the moment in my update method I am doing this because I am not sure of a better way: role_ids = params[:role_ids] user.roles.clear role_ids.each do |role| user.roles << Role.find(role) end unless role_ids.nil? So I am clearing all the entries out then looping threw all the role ids sent from the form via post, I also noticed that if all the checkboxes are checked and the form posted it keeps adding duplicate records, could anyone give some advice on a more efficent way of doing this?

    Read the article

  • Ruby-on-Rails: Multiple has_many :through possible?

    - by williamjones
    Is it possible to have multiple has_many :through relationships that pass through each other in Rails? I received the suggestion to do so as a solution for another question I posted, but have been unable to get it to work. Friends are a cyclic association through a join table. The goal is to create a has_many :through for friends_comments, so I can take a User and do something like user.friends_comments to get all comments made by his friends in a single query. class User has_many :friendships has_many :friends, :through => :friendships, :conditions => "status = #{Friendship::FULL}" has_many :comments has_many :friends_comments, :through => :friends, :source => :comments end class Friendship < ActiveRecord::Base belongs_to :user belongs_to :friend, :class_name => "User", :foreign_key => "friend_id" end This looks great, and makes sense, but isn't working for me. This is the error I'm getting in relevant part when I try to access a user's friends_comments: ERROR: column users.user_id does not exist : SELECT "comments".* FROM "comments" INNER JOIN "users" ON "comments".user_id = "users".id WHERE (("users".user_id = 1) AND ((status = 2))) When I just enter user.friends, which works, this is the query it executes: : SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users".id = "friendships".friend_id WHERE (("friendships".user_id = 1) AND ((status = 2))) So it seems like it's entirely forgetting about the original has_many through friendship relationship, and then is inappropriately trying to use the User class as a join table. Am I doing something wrong, or is this simply not possible?

    Read the article

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