I am trying to enter a foreign key value along with data collected from a form. The form data is submitting perfectly, but the foreign key is always entering as 1. I have tried several ways of entering the info, my current create method attempt is below:
def create
@product = Product.new(params[:product])
@username = User.select("company").where("email= ?", current_user.email.to_s)
@cid = User.select("id").where("company= ?", @username)
if @username != nil
@product.company_id = @cid
@product.save
end
end
Also, the find_by_something (and to_i) method throws up a No Such Method error, so I have used the above query syntax as a work around. If anyone can explain that as an aside…
Edit, The models: User Model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
# Setup accessible (or protected) attributes
attr_accessible :email, :password, :password_confirmation, :remember_me, :company
validates :company, :presence => true
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :timeoutable
after_save :correspond
def correspond
c = Company.find_or_create_by_name(self.company)
end
end
Company Model:
class Company < ActiveRecord::Base
has_many :product, :foreign_key => 'company_id', :class_name => 'Product'
end
Product Model
class Product < ActiveRecord::Base
belongs_to :company
validates :brand, :presence => true
end
Dan’s answer above is correct, but as a simpler version of it, to create the association you’re describing you need:
The Product and User tables need a column called
company_id.That’s it! Now ActiveRecord will associate the objects intelligently on your behalf, and you can do things like:
The best way to understand how all these relationships work is to play with them in the console. Try things like:
and so on…
Lastly, a thought: You would benefit immensely from reading an introductory book on Rails. I recommend ‘Beginning Rails 3‘. It’s a fast read, you could work through it in a weekend, and it will make the big picture of how and WHY rails works the way it works very clear to you. The time spent reading the book will QUADRUPLE your productivity and the speed at which you learn more advanced stuff, because you’ll be starting with a solid foundation and approaching problems “the rails way.”
Your problem today was definitely a case of “you’re doing it wrong”, which doesn’t mean there’s anything wrong with your logic, just that you’re making a simple problem much more difficult by trying to reinvent the wheel unnecessarily. Learning “the rails way” will make you much more productive, and will make the whole thing a lot more fun.