简体   繁体   English

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

[英]How to create an association between two rails models

This is a newbie question, but I'm still learning how to create an association between two models in rails. 这是一个新手问题,但我仍在学习如何在Rails中的两个模型之间创建关联。 I have a user model and a journal_entry model. 我有一个用户模型和一个journal_entry模型。 The journal entries belong to the user and the user has_many journal entries. 日记条目属于用户,而用户has_many日记条目。 I've created migrations that look like this: 我创建的迁移看起来像这样:

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

Here's what my User model looks like: 我的用户模型如下所示:

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

And here's what my journal_entry model looks like: 这是我的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

But when I go to create a new journal entry at /journal_entries/new I just a validation error that says "User can't be blank". 但是,当我在/journal_entries/new上创建新日记帐分录时,我只是出现一个验证错误,提示“用户不能为空”。 So the user_id is not getting added to the journal entry even though I'm logged in and there is a user_id column in my db/schema.rb: 因此,即使我已登录,并且在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

Also, this is the form that I'm using on journal_entries/new to create the journal entry: 另外,这是我在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? 我是否需要将user_id添加为表单上的隐藏字段?

i bet, that u forget something like 我敢打赌,你会忘记像

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 model should look like 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

This should work! 这应该工作!

您需要将user_id添加到您的attr_accessible调用中,如果您查看日志,则可能警告您无法大规模分配它。

Ok, so I got this working by adding the user to the create action in my journal_entries_controller.rb. 好的,因此通过将用户添加到我的journal_entries_controller.rb中的create动作中来完成了这项工作。 Here's the code I used, but is this the "rails way" to do this? 这是我使用的代码,但这是执行此操作的“轨道方式”吗?

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

you have it right this time. 这次你做对了。 You added the user association to the journal model which loads the user in the controller before displaying it in the view. 您将用户关联添加到日记模型中,该模型将用户加载到控制器中,然后再在视图中显示它。 You do need the hidden fields in your form which you added, since you are using a stateless protocol. 由于使用的是无状态协议,因此您确实需要在表单中添加隐藏字段。 On the update/create action, double check that the user posting is the user using and save. 在“更新/创建”操作上,仔细检查用户发布的用户是使用并保存的用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM