如何在两个rails模型之间创建关联

这是一个新手问题,但我还在学习如何在rails中创建两个模型之间的关联。 我有一个用户模型和一个journal_entry模型。 日记帐分录属于用户,用户拥有多个日记帐分录。 我创建了如下所示的迁移:

class AddJournalEntriesToUsers < ActiveRecord::Migration def change add_column :journal_entries, :user_id, :integer end end class AddIndexToJournalEntries < ActiveRecord::Migration def change add_index :journal_entries, [:user_id, :created_at] end end 

这是我的用户模型的样子:

 class User  "should match confirmation", :if => :password validates_length_of :password, :minimum => 3, :message => "password must be at least 3 characters long", :if => :password validates_presence_of :password, :on => :create validates_presence_of :email validates_uniqueness_of :email end 

这是我的journal_entry模型的样子:

 class JournalEntry < ActiveRecord::Base attr_accessible :post, :title, :user_id belongs_to :user validates :user_id, presence: true default_scope order: 'journal_entries.created_at DESC' end 

但是当我去/journal_entries/new创建一个新的日记条目时,我只是一个validation错误,上面写着“用户不能为空”。 所以即使我已经登录并且我的db / schema.rb中有user_id列,user_id也没有被添加到日记条目中:

 create_table "journal_entries", :force => true do |t| t.string "title" t.text "post" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.integer "user_id" end 

另外,这是我在journal_entries / new上用来创建日记条目的表单:

   

prohibited this journal_entry from being saved:



我在这里想念的是什么? 我是否需要将user_id添加为表单上的隐藏字段?

我打赌,你忘记了类似的东西

 def create @journal_entry = @user.journal_entries.build(params[:journal_entry]) # @journal_entry = current_user.journal_entries.build(params[:journal_entry]) if @journal_entry.save .. 

journal_entry模型应该是这样的

 class JournalEntry < ActiveRecord::Base attr_accessible :post, :title, :user_id belongs_to :user validates :user_id, presence: true default_scope order: 'journal_entries.created_at DESC' end 

这应该工作!

您需要将user_id添加到attr_accessible调用,如果您查看日志,它可能会警告您无法批量分配它。

好的,所以我通过将用户添加到我的journal_entries_controller.rb中的create动作来实现这一点。 这是我使用的代码,但这是“轨道方式”来做到这一点?

 def create @user = current_user @journal_entry = @user.journal_entries.build(params[:journal_entry]) if @journal_entry.save flash[:success] = "Journal entry created!" end end 

你这次没错。 您已将用户关联添加到日记模型,该日记模型将用户加载到控制器中,然后在视图中显示它。 您确实需要添加表单中的隐藏字段,因为您使用的是无状态协议。 在更新/创建操作上,仔细检查用户发布是否是用户使用和保存。