2011-09-09 35 views
0

我知道我是這個新手,並且我不值得,但是有人可以向我解釋爲什麼我得到一個沒有方法錯誤?這就是我所做的。我爲我的數據庫生成了一個新的遷移到我現有的Rails應用程序,遷移被稱爲「配置文件」。我運行db:migrate,然後繼續編輯我以前的「new.html.erb」表單。代碼如下所示:爲什麼我在我的Rails應用程序中收到No Method Error?

class CreateProfiles < ActiveRecord::Migration 
    def self.up 
    create_table :profiles do |t| 
     t.string :major 
     t.string :year 
     t.string :books_sell 
     t.string :books_buy 
     t.string :facebook 
     t.string :restaurants 
     t.string :interests 

     t.timestamps 
    end 
    add_index :profiles, :major 
    add_index :profiles, :year 
    add_index :profiles, :books_sell 
    add_index :profiles, :books_buy 
    add_index :profiles, :facebook 
    add_index :profiles, :restaurants 
    add_index :profiles, :interests 
    end 

    def self.down 
    drop_table :profiles 
    end 
end 

基本上,我增加了輪廓部分到我的應用程序,但我得到這個:

undefined method `major' for #<User:0x00000100b6e030> 
    Extracted source (around line #23): 

    20: </div> 
    21: <div class="field"> 
    22:  <%= f.label :"major" %><br /> 
    23:  <%= f.text_field :major %> 
    24: </div> 

這是我的意見/用戶/ new.hmtl.erb文件:

<h1>Sign up</h1> 

<%= form_for(@user) do |f| %> 
    <%= render 'shared/error_messages', :object => f.object %> 
    <div class="field"> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </div> 
    <div class="field"> 
    <%= f.label :email %><br /> 
    <%= f.text_field :email %> 
    </div> 
    <div class="field"> 
    <%= f.label :password %><br /> 
    <%= f.password_field :password %> 
    </div> 
    <div class="field"> 
    <%= f.label :password_confirmation, "Confirmation" %><br /> 
    <%= f.password_field :password_confirmation %> 
    </div> 
    <div class="field"> 
    <%= f.label :"year" %><br /> 
    <%= f.text_field :year %> 
    </div> 
    <div class="field"> 
    <%= f.label :"major" %><br /> 
    <%= f.text_field :major %> 
    </div> 
    <div class="actions"> 
    <%= f.submit "Sign up" %> 
    </div> 
<% end %> 

什麼是缺失?

+1

您的表單用於'User'模型,而您的遷移是針對'Profile'模型。這可能是你的問題嗎? –

+0

@Benoit Garret,我認爲你會發現。我會研究這一點。 – Tony

+0

嚴重的是,不要爲新手而道歉。閱讀這個線程關於新手問題:http://meta.stackexchange.com/questions/97327/can-i-ask-newbie-and-basic-questions-in-stack-overflow。 –

回答

1

這裏的問題是,我以前有用戶模式下完成的表單視圖。我想強調這種形式,所以我創建了一個名爲profile的新遷移。我這樣做是因爲我無法手動回滾用戶模型的遷移,並且只能處理字符串和列。

但是,從用戶模型下的配置文件模型添加文本字段會導致錯誤。

我做的是我創建了一個Add_xxx_to_yyy遷移,它允許我將列添加到先前創建的遷移中,沒有任何問題。我用下劃線rails generate migration Add_profile_to_User,因爲我在軌道3.0(它沒有工作,當我做Addprofiletouser)。 Etvoilà!

+1

您可以使用'rake db:rollback STEP = n'回滾遷移,其中'n'是您想要回滾的遷移數。在開發時,我總是修改現有的遷移,使用回滾+遷移。 –

+1

至於遷移代,你可以在駱駝大小寫('AddProfileToUser')或蛇形大小寫('add_profile_to_user')中指定遷移名稱。 –

0

您已將您的遷移粘貼到Profile模型。我想,在您的@user變量中,您有User模型的新實例。

而且因爲沒有方法或您的用戶自定義屬性major,你看到的投訴「未定義的方法......」

相關問題