I have a small app that allows users to upload recipes and save favourite recipes. I have a separate model called country that has all the countries of the world within it which then allows users to select one from a dropdown.
Initially I had the association as
recipe
has_one :country
country
belongs_to :recipe
After some research the correct association is
recipe
belongs_to :country
country
belongs_to :recipe
The foreign key country_id going within the recipe model.
I'm going to do some more reading but was wondering if someone could explain as to why it is this association and not the first one
I guest you want to build association like this:
country can has many recipe
recipe belongs to one country
If so, you should define association is:
country:
has_many :recipes
recipe:
belongs_to :country
And i think your second association is also incorrect.
When you define belongs_to :country in Recipe model, it means your Recipe table must have a column called country_id. It is a foreign key to Country model.
In the first define association, the Country model will have a column called recipe_id, so, every country just has only one recipe, that's not what you want, right? Why it's not work? Because with one country you have only one record, so one country can have only one recipe, accessed through recipe_id.
With first association, your association is One-to-One (One Country has one Recipe), while you actually want your association is One-to-Many ( One Country has Many Recipe). So it's reason why first association not works (second too).
The main thing you need to remember here is, what model you put a belongs_to association, that model will have a column called 'association name'_id. The different between using has_one and belongs_to only is where you put foreign key and the meaning of association. Check here to clearer.
I'm not sure this is the right association. The belongs_to association is always used in the model that has the foreign key (see here). Having foreign keys in both tables is not a good idea, as far as I can think. Can you explain why you think the last association is correct?
BTW, I think that the correct association is:
country has_many recipes and recipe belongs_to country
Related
I'm new to active record, I want to know the difference between has_one and belongs_to in associations.
Can anyone explain with a good example?
I want examples for has_one associations without using belongs_to in the second model.
The difference is in where the foreign key is stored.
So for example if a post belongs to a user, the post table will have a column user_id so the post knows which user it belongs to.
has_one only makes methods like some_user.post available.
See also: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Is+it+a+belongs_to+or+has_one+association%3F
I've been trying to wrap my head around these associations and I've run into a bit of a snag. The app I'm working on has 2 models at the moment: Ingredient, and Recipe. The logic behind each is as follows:
The Ingredient model contains info on food items, such as name, bulk price, etc.
The Recipe model contains the name of the recipe, preparation instruction, and a list of ingredients (along with the amount required for the recipe).
After digging through some of the questions on here, and watching a few railscasts I've determined that a has_many_through relationship may be better for what I'm attempting to do, since I'd like to include additional info about the ingredient in the recipe (amount required).
Based on my limited experience in this area, I'd like to approach it like this:
class Recipe < ActiveRecord::Base
has_many :ingredients_recipes
has_many :ingredients, :through => :ingredients_recipes
end
class Ingredient_Recipe < ActiveRecord::Base
belongs_to :ingredient
belongs_to :recipe
end
class Ingredient < ActiveRecord::Base
has_many :ingredients_recipes
has_many :recipes, :through => :ingredients_recipes
end
Where the ingredients_recipes table would have fields similar to this: recipe_id, ingredient_id, ingredient_qty (for storing how much of a particular ingredient is in a recipe)
Is this the proper way to approach it code-wise, based on the functionality I mentioned above? Any help would be greatly appreciated. Thanks!
Edit
I'd also like to be able to add these new ingredients to the recipe from the recipe form. Would this require anything extra, like having to do accepts_nested_attributes_for the through table, or is this something that Rails would handle on it's own?
The :has_many through approach works best when one object can have zero or many other objects connected & there are some properties associated with each connection.
For example, in your case, you'd be storing the amount of each ingredient along with the recipe_id an ingredient_id in the Connections table.
So, it looks GOOD to me. :)
However, you should consider naming your Ingredient_Recipe table to something more appropriate.
I'm having trouble finding a good tutorial on how to define basic foreign key relationships between models. suppose I have a User model and a Game model..
I would like to define two fields in the Game model - host_id and visitor_id which are mapped via foreign key relationship to the User model. The IDs of the 'host' and 'visitor' fields of the Game class basically define the two players which will engage in a peer-to-peer game... and those fields need to be mapped to actual users of the application as defined in the User model by userID..
Thank you!
Did try this http://guides.rubyonrails.org/association_basics.html?
I think it could be like this:
class User
belongs_to :game
end
class Game
has_one :host_user, :class_name => "User"
has_one :visit_user, :class_name => "User"
end
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.
A phone has many messages.
An email address has many messages.
A message either belongs to a phone, email, or neither. The belongs_to association is optional.
The following associations seem to work fine for these relationships:
Phone model has_many :messages
Email model has_many :messages
Message model does NOT have belongs_to :phones, :email
Is this okay or is there some proper way to specify a "can_belong_to" relationship?
It is completely correct unidirectional relation. Using both is sometimes called "curcular dependency" by some purists and may cause problems when using validates_associated.
From the other side using only has_many :messages may be not enough when you want retrieve phone information from one message. Generally it is matter of convenience.
The model with the belongs_to associations holds the foreign keys (e.g. messages table would have phone_id and email_id columns).
The belongs_to association combined with has_many lets you easily access associated records:
phone.messages
message.phone
So without the belongs_to and FK columns, the has_many association isn't very useful.
It seems like in this case you may want a many-to-many relationship such as has_and_belongs_to_many as a message can have many recipients.