In my Rails app I have classes that depend on one another, ParkingSpace and Parking Lot.
A ParkingLot has many ParkingSpaces and the ParkingSpace belongs to a ParkingLot.
I want to ensure that the same ParkingSpace can't be inserted into the ParkingLot again.
Typically, I would use a uniqueness validation to ensure that the ParkingSpace can't be repeated parking space have very generic names
ParkingLot with id:1 can have ParkingSpaces 1, 2 and 3 on it.
ParkingLot with id:2 can also have ParkingSpaces 1, 2 and 3 on it.
But the above parking lots should not be able to have two parking spaces with the same name.
How can I validate this in Rails?
How can I validate this at the database level?
I'm considering joining the two fields together in a unique way and then calling unique on that. Is this a valid approach? (Not exactly sure how to do this at the database level, but all my validations need to be present there.)
(using Postgres)
Assuming your parking space and an identifier (like a name), you would do something in the ParkingSpace class like:
class ParkingSpace < ActiveRecord::Base
belongs_to :parking_lot
validates_uniqueness_of :name, :scope => :parking_lot_id
end
well since parking # belongs to to parking lot. you would add a uniquness validation to the parking lot model that validates unqiuness of :parkingspace_id
you're creating a parking spot object that has a unique id so parking space #1 would be id = 1. if you validate the uniquness of the id then you will ensure that another parking lot can add it.
Seems like this gem: "Sexy PG constraints is closer to the answer."\
https://github.com/maxim/sexy_pg_constraints
Feel free to add to it, or explain anything from it.
From the documentation
Multi-column constraints
Say you have the same table “books” only now you want to tell your
Postgres to make sure that you should never have the same title +
author_id combination. It means that you want to apply uniqueness to
two columns, not just one. There is a special syntax for working with
multicolumn constraints.
class AddConstraintsToBooks < ActiveRecord::Migration
def self.up
constrain :books do |t|
t[:title, :author_id].all :unique => true # Notice how multiple columns are listed in brackets.
end
end
def self.down
deconstrain :books do |t|
t[:title, :author_id].all :unique
end
end
end
It’s important to note that you shouldn’t mix multicolumn constraints
with regular ones in one line. This may cause unexpected behavior.
Related
I have a Rails database for reviewing things at a school. My tables are School, Major, Course, Instructor, Review. The way my team currently has the Review table set up, there are non-nullable foreign keys to each one of the other tables.
My issue with this is that to submit a new review the user would want to fill in only 1 of those foreign keys. Is there a way to do this with Rails? Even if there is, it seems like this would be a better use case for Instructor_Review, Course_Review, etc tables. That also has the (very nice) benefit of being able to customize table attributes for each review.
However, if we were to break up Review into multiple tables, is there a mechanism in Rails for having common columns? The overall_rating attribute would need to be included for every type of review, should the attributes just have the same name or is there a way for Rails to have table Subclasses (I know there is in SQL...)
I wouldn't create different models for the different review types if they are similar (apart from the thing the review is about). This is probably a source of duplication which should be avoided.
Instead, you could use a polymorphic association. Your review model has one thing the review belongs to (be it a school, a teacher, or an instructor). So lets model it like that. Give it a reference to that thing and the type of that thing (so that Rails knows which class it belongs to).
With polymorphic associations, your classes can be linked like this:
class Review < ActiveRecord::Base
belongs_to :reviewable, polymorphic: true
belongs_to :user
# ...
end
class School < ActiveRecord::Base
has_many :reviews, as: :reviewable
end
class Teacher < ActiveRecord::Base
has_many :reviews, as: :reviewable
end
On the database-level this means that your review table just needs one foreign key to point at the reviewable thing (plus one type column). The review-migration would look like this:
class CreateReviews < ActiveRecord::Migration
def change
create_table :reviews do |t|
t.references :user, index: true
t.references :reviewable, polymorphic: true, index: true, null: false
t.timestamps null: false
end
end
end
polymorphic: true lets Rails create the id- and type-column.
For details, please refer to the ActiveRecord documentation.
PS: There is also a RailsCast covering this issue. But beware: It's from 2009 - pretty old, but (from a quick glimpse at it) it should still work.
You are looking for polymophic relationships. Basically add a type column on the review and then you have to wire it up correctly. Here is a great article for that.
http://www.gotealeaf.com/blog/understanding-polymorphic-associations-in-rails
The review table will then have your common reviewable columns that will be shared. The next part is a little more complicated. You would then setup a review to have an extension.
To explain the extension, this is normally done when you have an entity that can either be a group or user (similar to how your InstructoreReview and CourseReview will by types of reviews). Those groups/users will have a profile that is similar to the extension of the review.
The ReviewExtension will have it's own table per review that you are extending and most of the time those extensions in their own review_extensions folder under models.
Once that is done you will delegate the common getter and setter methods you are wanting to the extension.
Hopefully this will at least give you enough to get going.
I'm trying to do something extremely simple but can't find a solution in RailsGuides.
I have two tables, words and flavors. There's a dictionary's worth of words, and only about 10 flavors. I want each word to have a flavor.
I've tried many combinations of flavor_id and word_id in the migrations, and has_one and belongs_to in the models, but always run into problems. Giving the has_one to the word isn't right because then each flavor could only be associated to one word. Flipping the has_one doesn't help because it prevents me from doing things like word.flavor = Flavor.some_flavor.
Is there a method for handling such scenarios?
Update: I had to drop both tables and recreate them, and David Underwood's solution worked.
Here are some class definitions that will work:
class Word < ActiveRecord::Base
belongs_to :flavor
end
class Flavor < ActiveRecord::Base
has_many :words
end
In your schema, you want the words table to have a flavor_id column. You don't need a foreign key on the flavors table.
The key is that each word is associated with a single flavor, and a single flavor can be associated with many words.
You can now call word.flavor to get the flavor of a word as well as flavor.words to get an array of words with that flavor.
I'm doing my first rails(3) application.
Associations don't make sense. First, even the rails guides don't
really explain what they do, they just explain how to use them.
From what I gather, associations do two things:
a) Allow ActiveRecord to optimize the structure of the database.
b) Allow ActiveRecord to offer an alternate ruby syntax for
joins and the like (SQL queries). I want this.
I'm trying to understand associations, and how to properly use them. Based
on the example below, it seems like associations are 'broken' or at least
the documentation is.
Consider a trivial version of my application. A teacher modifying wordlists
for study.
There are 3 relevant tables for this discussion. For clarity, I've simply
included the annotate(1) tool's definition of the table, and removed
unnecessary fields/columns.
A wordlist management table:
Table name: wordlist_mgmnt_records
id :integer not null, primary key
byline_id :integer(8) not null
A table that maps words to a word list:
Table name: wordlists
wordlist_mgmnt_id :integer not null
word_id :integer not null
We don't actually care about the words themselves. But we do care about
the last table, the bylines:
Table name: bylines
id :integer(8) not null, primary key
teacher_id :integer not null
comment :text not null
Bylines record who, what tool was used, where, when, etc. Bylines are
mainly used to trouble shoot what happened so I can explain to users what
they should have done (and/or repair their mistakes).
A teacher may modify one or more word list management records at a time
(aka single byline). Said another way, a single change may update multiple
word lists.
For wordlist_mgmnt_records the associations would be:
has_many :bylines # the same byline id can exist
# in many wordlist_mgmnt_records
But what's the corresponding entry for bylines?
The Beginning Rails 3 (Carneiro, et al) book says:
"Note: For has_one and has_many associations, adding a belongs_to
on the other side of the association is always recommended. The
rule of thumb is that the belongs_to declaration always goes in
the class with the foreign key."
[ Yes, I've also looked at the online rails guide(s) for this. Didn't
help. ]
For the bylines table/class do I really want to say?
belongs_to :wordlist_mgmnt_records
That really doesn't make sense. the bylines table basically belongs_to
every table in the data base with a bylines_id. So would I really say
belongs_to all of them? Wouldn't that set up foreign keys in all of the
other tables? That in turn would make changes more expensive (too many
CPU cycles) than I really want. Some changes hit lots of tables, some of
them very large. I prize speed in normal use, and am willing to wait to
find bylines without foreign keys when using bylines for cleanup/repair.
Which brings us full circle. What are associations really doing in rails,
and how does one use them intelligently?
Just using associations because you can doesn't seem to be the right
answer, but how do you get the added join syntax otherwise?
I'll try to help your confusion....
A byline can have multiple wordlist_mgmnt_records, so defining the has_many there seems to make sense.
I'm not sure I understand your confusion in the other direction. Since you have defined the attribute wordlist_mgmnt_records.byline_id, any given wordlist_mgmnt_record can only 'have' (belong_to) a single byline. You're simply defining the crows foot via ruby (if you like database diagrams):
wordlist_msgmnt_records (many)>>----------(one) byline
Or read in english: "One byline can have many wordlist_mgmnts, and many individual wordlist_mgmnt's can belong to a single byline"
Adding the belongs_to definition to the wordlist_mgmnt model doesn't affect the performance of the queries, it just let's you do things like:
#record = WordlistMgmntRecord.find(8)
#record_byline = #record.byline
Additionally you're able to do joins on tables like:
#records = WordlistMgmntRecord.joins(:byline).where({:byline => {:teacher_id => current_user.id}})
Which will execute this SQL:
SELECT wordlist_mgmnt_records.*
FROM wordlist_mgmnt_records
INNER JOIN bylines
ON wordlist_mgmnt_records.byline_id = bylines.id
WHERE bylines.teacher_id = 25
(Assuming current_user.id returned 25)
This is based off of your current DB design. If you find that there's a way you can implement the functionality you want without having byline_id as a foreign key in the wordlist_mgmnt_records table then you would modify your models to accomodate it. However this seems to be how a normalized database should look, and I'm not really sure what other way you would do it.
I am working on an app that will manage students enrolled in a course. The app will have users who can log in and manipulate students. Users can also comment on students. So three of our main classes are Student, User, and Comment. The problem is that I need to associate individual comments with both of the other models: User and Student. So I've started with some basic code like this...
class Student < ActiveRecord::Base
has_many :comments
end
class User < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :student
belongs_to :user
attr_accessible :comment
end
So in the comments table, a single record would have the following fields:
id
comment
student_id
user_id
created_at
updated_at
This presents several problems. First, the nice Rails syntax for creating associated objects breaks down. If I want to make a new comment, I have to choose between the foreign keys. So...
User.comments.create(attributes={})
OR
Student.comments.create(attributes={})
Another option is to arbitrarily pick one of the foreign keys, and manually add it to the attrs hash. So...
User.comments.create(:comment => "Lorem ipsum", :student_id => 1)
The problem with this option is that I have to list student_id under attr_accessible in my Comment model. But my understanding is that this poses a security risk since someone could technically come along and reassociate the comment with a different student using mass assignment.
This leads to a further question about data modeling in general using Rails. The app I'm currently building in Rails is one that I originally wrote in PHP/MySQL a few years ago. When I first studied SQL, great importance was placed on the idea of normalization. So, for example, if you have a contacts table which stores names and addresses, you would use a lot of foreign key relationships to avoid repeating data. If you have a state column, you wouldn't want to list the states directly. Otherwise you could potentially have thousands of rows that all contain string values like "Texas." Much better to have a separate states table and associate it with your contacts table using foreign key relationships. My understanding of good SQL theory was that any values which could be repeating should be separated into their own tables. Of course, in order to fully normalize the database, you would likely end up with quite a few foreign keys in the contacts table. (state_id, gender_id, etc.)
So how does one go about this in "the Rails way"?
For clarification (sorry, I know this is getting long) I have considered two other common approaches: "has_many :through =>" and polymorphic associations. As best I can tell, neither solves the above stated problem. Here's why:
"has_many :through =>" works fine in a case like a blog. So we have Comment, Article, and User models. Users have many Comments through Articles. (Such an example appears in Beginning Rails 3 from Apress. Great book, by the way.) The problem is that for this to work (if I'm not mistaken) each article has to belong to a specific user. In my case (where my Student model is here analogous to Article) no single user owns a student. So I can't say that a User has many comments through Students. There could be multiple users commenting on the same student.
Lastly, we have polymorphic associations. This works great for multiple foreign keys assuming that no one record needs to belong to more than one foreign class. In RailsCasts episode #154, Ryan Bates gives an example where comments could belong to articles OR photos OR events. But what if a single comment needs to belong more than one?
So in summary, I can make my User, Student, Comment scenario work by manually assigning one or both foreign keys, but this does not solve the issue of attr_accessible.
Thanks in advance for any advice!
I had your EXACT question when I started with rails. How to set two associations neatly in the create method while ensuring the association_ids are protected.
Wukerplank is right - you can't set the second association through mass assignment, but you can still assign the association_id directly in a new line.
This type of association assignment is very common and is littered throughout my code, since there are many situations where one object has more than one association.
Also, to be clear: Polymorphic associations and has_many :through will not solve your situation at all. You have two separate associations (the 'owner' of a comment and the 'subject' of a comment) - they can't be rationalised into one.
EDIT: Here's how you should do it:
#student = Student.find_by_id(params[:id])
#comment = #student.comments.build(params[:comment]) #First association is set here
#comment.user = current_user #Second association is set here
if #comment.save
# ...
else
# ...
end
By using the Object.associations.build, Rails automatically creates a new 'association' object and associates it with Object when you save it.
I think polymorphic association is the way to go. I'd recommend using a plugin instead of "rolling your own". I had great results with ActsAsCommentable (on Github).
As for your attr_accessible problem: You are right, it's more secure to do this. But it doesn't inhibit what you are trying to do.
I assume that you have something that holds the current user, in my example current_user
#student = Student.find(params[:id])
#comment = Comment.new(params[:comment]) # <= mass assignment
#comment.student = #student # <= no mass assignment
#comment.user = current_user # <= no mass assignment
if #comment.save
# ...
else
# ...
end
The attr_accessible protects you from somebody sneaking a params[:comment][:student_id] in, but it won't prevent the attribute from being set another way.
You still can get all comments of your users through the has_many :comments association, but you can also display who commented on a student thanks to the belongs_to :user association:
<h1><%= #student.name %></h1>
<h2>Comments</h2>
<%- #student.comments.each do |comment| -%>
<p><%= comment.text %><br />
by <%= comment.user.name %></p>
<%- end -%>
PLUS:
Don't over engineer your app. Having a state:string field is perfectly fine unless you want to do something meaningful with a State object, like storing all districts and counties. But if all you need to know a students state, a text field is perfectly fine. This is also true for gender and such.
Well, for the first part. If I understood your question correctly, I think, that since comments are listed within students controller, you should associate them through Student model (it just seems logical to me). However, to protect it from assigning wrong user id, you could do something like this
#student = Student.find params[:id]
#student.comments.create :user => current_user
current_user might be a helper that does User.find session[:user_id] or something like that.
has_many :through association doesn't make sense here. You could use it to associate User and Student through Comment, but not User and Comment through Student
Hope that helps.
Though my problem is specifically in Ruby on Rails, I'm also asking generally: I have a users table and want to designate some users to be students and others to be teachers. What is the best way to design the schema in this case?
Edit:
Though I originally accepted vonconrad's answer--it fits the original criteria--I have to reopen and adjust the question based on feedback from nhnb.
What should be done if students and/or teachers require additional (unique) attributes?
This greatly depends on how many the different attributes between the teacher and student there'll be as well as how often new unique attributes will be added or removed. If the case is that they will differ a lot, you have two choses:
Make two models, one for Student and one for Teacher and use ruby include to share any logic between the two models. Any associations that associate with a user, you would use a polymorphic association (has_many :user, :polymorphic => true)
Put the attributes in another table. For example: you'll have the users table and a user_attributes table. users would have id, user_type, username, etc. and user_attributes would have id, user_id, attribute_name, value.
If, however, your different attributes between the two users are few and pretty rock solid, you should just consider using Single Table Inheritance.
Good luck!
In this case, I'd simply go with a single boolean column called teacher. If true, the user is a teacher. If false, it's a student. No need to create another model.
If you want more than two roles (say, student, teacher, administrator, janitor(?)), you can add another model called UserGroup. You'll also have to create a column in the users table called user_group_id. In the new model, you have a single row for each of the roles. Then, you specify the following relationships:
class User < ActiveRecord::Base
belongs_to :user_group
end
class UserGroup < ActiveRecord::Base
has_many :users
end
This will allow you to assign each user to a specific group.