0

我陷入了一個小問題,但對於我試圖弄清楚我做錯了什麼已經很久了。我的場景是我有一個現有的模型user,現在我創建了另一個名爲`user_comment'的模型。has_many中的關聯,屬於rails中的關聯

用戶模式:

class User < ActiveRecord::Base 
has_many :user_comments 
end 

USER_COMMENT型號:

class UserComment < ActiveRecord::Base 
    belongs_to :user 
    end 

遷移文件:

class CreateUserComments < ActiveRecord::Migration 
    def change 
    create_table :user_comments do |t| 
     t.integer :user_id 
     t.string :comments 
     t.timestamps 
    end 
    end 
end 

運行rake db:migrate後我去rails console,然後我在下面提及的細節創建建立兩個表之間的關係,我做了下面的事情NG並沒有什麼工作

obj1= User.first 

我第一次加入新行中user_comments表,然後做..

obj2= UserComment.first 

obj1.obj2= obj2是給我

NoMethodError: undefined method `obj2=' for #<User:0x00000005f8e850> 
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activemodel-3.2.11/lib/active_model/attribute_methods.rb:407:in `method_missing' 
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/activerecord-3.2.11/lib/active_record/attribute_methods.rb:149:in `method_missing' 
    from (irb):3 
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands/console.rb:47:in `start' 
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands/console.rb:8:in `start' 
    from /home/insane/.rvm/gems/ruby-2.1.0/gems/railties-3.2.11/lib/rails/commands.rb:41:in `<top (required)>' 
    from script/rails:6:in `require' 
    from script/rails:6:in `<main>' 

請幫助我如何形成一個協會..

回答

1

哪裏SmileComment突然從何而來?

無論如何,有幾件事情出錯了。首先,我會將您的模型的名稱從UserComment更改爲Comment。評論屬於用戶的事實已經通過您的關聯明確了。調用User.first.user_comments看起來有點不方便。

讓我們從一個非常簡單的例子:

class User < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :user 
end 

像你一樣在你的遷移,評論需要爲user_id引用它屬於用戶。運行遷移,調用關聯後是死的簡單:

User.first.comments # Gives all comments belonging to that user 

或者:

Comment.first.user # Gives the user that belongs to that comment 
2

obj1.obj2= obj2是錯的,你需要一個空間之間en obj1.obj2=

但是ob1.obj2也沒有意義(在User中沒有obj2方法)。

對象添加到關聯,你可以這樣做:

user = User.first 
comment = UserComment.first 

# if both object are not nil, then you could do below 
user.user_commentes << comment 
1

obj1.obj2= obj2 =>自我指涉的循環?


你最好讀了Rails ActiveRecord associations指南 - 你會發現你與實際上是比較簡單的處理什麼正如@rails4guides.com描述補救

,你最好重新命名UserComment模型只是Comment(因爲這將允許你你需要的任何數據聯繫起來 - 如果你想擴展後):

#app/models/user.rb 
Class User < ActiveRecord::Base 
    has_many :comments 
end 

#app/models/comment.rb 
Class Comment < ActiveRecord::Base 
    belongs_to :user 
end 

這實際上是下降到relational database naming conventions,從而每個表的數據可以與另一個相關聯。他們這麼做foreign_keys - 這是Rails的是如何使用你的模型中定義的關聯創建的@user.comments喜歡:

class Comments < ActiveRecord::Migration 
    def change 
    create_table :comments do |t| 
     t.integer :user_id => this is the foreign_key, which means Rails can append these objects to your `user` object 
     t.string :comments 
     t.timestamps 
    end 
    end 
end 

所以,如果你想給用戶提供一組的意見,你只需要請從您的模型中調用User對象,並且由於Rails的ActiveRecord關聯通過您的模式自動調用任何關係數據,因此將comments附加到@user對象上,@user.comments