Reputation: 1057
I just studied ruby on rails today and I'd like some help on creating proper associations. I have these models:
Comment:
class Comment < ActiveRecord::Base
belongs_to :stammr_post
validates :stammr_post_id, presence: true
validates :content, presence: true
end
Post:
class StammrPost < ActiveRecord::Base
has_many :comments, :dependent => :destroy
validates :content, presence: true
end
The thing is, whenever I create a Comment, and I enter a Stammr_post_id that doesn't exist, rails still accepts it as valid. Isn't that supposed to be invalid since a comment belongs to Stammr_post? The stammr_post should exist first before a comment could be made. How do I resolve this? Is it supposed to be automatic? Did I make a typo somewhere? Or do I need to do manual validation for that? Sorry, I'm kinda new to Ruby on Rails. I'm a former grails developer and I was used to the automatic associations thing. @_@
Upvotes: 1
Views: 238
Reputation: 3903
The correct way to do this is create the Comment through the parents association. That way you are taking advantage of the association;
So instead of doing this;
@comment = Comment.new(:stammr_post_id => 123)
@comment.save
do this;
# Find the StammrPost first. You may want to replace params[:stammr_post_id]
# with your StammrPost id
@stammr_post = StammrPost.find(params[:stammr_post_id])
@comment = @stammr_post.comments.build()
@comment.save
Upvotes: 1
Reputation: 5929
You could validate associated belongs_to
object (stammr_post
) instead of database column (stammr_post_id
).
class Comment < ActiveRecord::Base
belongs_to :stammr_post
validates :stammr_post, :content, presence: true
end
Upvotes: 0