rails mysql error issue - possibly tables not linked
I've been working through some issues getting rails to behave nicely with sqllite, and decided to move over to mysql.
I ran my rake db:create and rake db:schema, and assumed everything was ok, but then mysql show tables displayed a complete table was missing.
I created a migration with the create table details and ran rake db:migrate, and now the all the tables show up.
Unfortunately, it appears that the link betw开发者_如何学Goeen the tables didn't work.
The app is a fairly simple recipe app. The tables are
recipes ingredients steps
the ingredients table was the one which was not created in the db:create or db:schema.
I created the ingredients table with
class AddIngredientsTable < ActiveRecord::Migration def self.up create_table :ingredients do |t| t.string :ingredient t.float :amount t.string :measure t.string :description end end
In my recipes model i have has_many :ingredients, and my ingredients model has belongs_to :recipe
The error I'm getting is
Mysql::Error: Unknown column 'ingredients.recipe_id' in 'where clause': SELECT `ingredients`.* FROM `ingredients` WHERE (`ingredients`.recipe_id = 1)
and of course, the error is correct that a recipe_id field does not exist in either table. But I don't have such a request in the controller either which reads simply
def show @recipe = Recipe.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @recipe } end end
Any suggestions as to what to look for and why this problem might have occured, and how to fix it?
I'd prefer not to manually write out the sql as my understanding is that at this stage that isn't the rails way, though I am familiar with sql so could do this.
Rails uses a lot of conventions. In this case you're hitting the rule that has_many :ingredients
on Recipe
means that the ingredients
table must have recipe_id
. Obviously you probably want ingredients shared between many recipes, and so for that you'll want has_and_belongs_to_many
with a join table (which you will create another migration for).
I suggest you start with this guide for a comprehensive overview of how this works in Rails.
精彩评论