这是一个新手问题,但我仍在学习如何在 Rails 中的两个模型之间创建关联。我有一个用户模型和一个 journal_entry 模型。日记条目属于用户并且用户有_many 日记条目。我创建了如下所示的迁移:
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 < ActiveRecord::Base
authenticates_with_sorcery!
attr_accessible :email, :password, :password_confirmation
has_many :journal_entries, dependent: :destroy
validates_confirmation_of :password, :message => "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
我只是一个验证错误,上面写着“用户不能为空”。因此,即使我已登录并且我的 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 上用来创建日记条目的表单:
<%= form_for(@journal_entry) do |f| %>
<% if @journal_entry.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@journal_entry.errors.count, "error") %> prohibited this journal_entry from being saved:</h2>
<ul>
<% @journal_entry.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :post %><br />
<%= f.text_area :post %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
What am I missing here? Do I need to add the user_id as a hidden field on the form?