2011-08-16 39 views
0

我真的面临着压力,对Rails来说全新。项目在两天内到期。无法访问相关表格

我已经在我的数据库user = user.find(1)中输入的用户在Rails控制台上进行了搜索并返回。

用户has_many食谱 食谱属于用户....分别在用户和配方模型中定义。

我收到错误。

未定义的方法“配方”的用户?

这是我建立了我的用户

class CreateUsers < ActiveRecord::Migration 
    def self.up 
    create_table :users do |t| 
    t.integer "position" 
    t.boolean "visible", :default => false 
    t.string "restaurant_name", :limit => 25 
    t.string "username", :limit => 25 
    t.string "password", :limit => 50 
    t.string "hashed_email", :default => "", :null => false 
    t.string "address1", :limit => 80 
    t.string "address2", :limit => 80 
    t.string "address3", :limit => 80 
    t.string "county", :limit => 40 
    t.string "telephone", :limit => 40 
    t.text "web address", :limit => 60 
    t.string "photo_path", :limit => 100 
    t.text "description", :limit => 2000 
    t.text "salt", :string, :limit => 50 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :users 
    end 
end 

配方

class CreateRecipes < ActiveRecord::Migration 
     def self.up 
     create_table :recipes do |t| 
     t.integer "user_id" 
     t.string "recipe_name", :limit => 100 
     t.integer "greedy_type", :default => 0 
     t.string "photo_path", :limit => 40 
     t.text "description", :limit => 400 
     t.text "recipe", :limit => 4000 
     t.integer "ingredient1", :limit => 40 
     t.integer "ingredient2", :limit => 40 
     t.integer "ingredient3", :limit => 40 
     t.integer "ingredient4", :limit => 40 
     t.string "permalink" 
     t.integer "position" 
     t.boolean "visible", :default => false 
     t.timestamps 
    end 
    add_index("recipes", "user_id") 
    add_index("recipes", "permalink") 
    end 

    def self.down 
    drop_table :recipes 
    end 
end 

users.rb的

class Users < ActiveRecord::Base 
     has_many :recipes 
    end 

recipe.rb

class Recipes < ActiveRecord::Base 
     belongs_to :users 
     has_many :restaurants 
    end 

ERROR

irb(main):005:0> users.recipe 
NoMethodError: undefined method `recipe' for #<Users:0x599ebc0> 
     from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activemodel-3.0.9/lib/active_model/attribute_methods.rb: 
392:in `method_missing' 
     from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activerecord-3.0.9/lib/active_record/attribute_methods.r 
b:46:in `method_missing' 
+0

请出示您的'用户'和'食谱'类。 – Chowlett

+0

你为什么要在用户模型中存储recipe_id?有了has_many关系,您应该将user_id放在recpies模型中。顺便说一下,你是否以明文形式存储密码? – atmorell

回答

7

如果User的has_many recipes,为什么你加场recipe_iduser?您应该将user_id字段添加到Recipe类表中。在创建recipe后,只需存储user_id,这就是你所需要的。干杯!

+0

非常感谢你的帮助。我重建了whoel应用程序。 – duvlinia

+0

我重新加载了我的更改 - 仍然是相同的错误 – duvlinia

+0

上面加载的新代码 – duvlinia

2

如用户有许多食谱,

你必须写东西喜欢拿第一用户配方..

recipe = user.recipes.first 

和USER_ID存储在配方表。