【发布时间】:2014-02-28 14:52:56
【问题描述】:
我有一个简单的预订系统:
class User < ActiveRecord::Base
has_many :appointments
has_many :bookings
end
class Appointment < ActiveRecord::Base
belongs_to :booking
belongs_to :user
end
class Booking < ActiveRecord::Base
belongs_to :course
belongs_to :user
end
等等……
约会表:
add_index "appointments", ["booking_id"], name: "index_appointments_on_booking_id"
add_index "appointments", ["user_id"], name: "index_appointments_on_user_id"
create_table "appointments", force: true do |t|
t.integer "booking_id"
t.integer "user_id"
t.boolean "confirmed"
t.boolean "attended"
t.datetime "created_at"
t.datetime "updated_at"
end
为特定课程创建记录的表单:
<%= form_for([@course, @booking]) do |f| %>
<% if @booking.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@booking.errors.count, "error") %> prohibited this booking from being saved:</h2>
<ul>
<% @booking.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :course_id, :value => @course.id %>
<div class="field">
<%= f.label "Name" %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label "Description" %><br>
<%= f.text_area :description %>
</div>
<h3>When?</h3>
<div class="field">
<%= f.date_select :start_date %>
</div>
<div class="field">
<%= label_tag "until" %>
<%= check_box_tag(:end_date) %>
</div>
<div class="field" id="end_date_field", style="display:none">
<%= f.date_select :end_date %>
</div>
<div class="field">
<%= f.label "starts at" %><br>
<%= f.time_select :start_time %>
</div>
<div class="field">
<%= f.label "ends at" %><br>
<%= f.time_select :end_time %>
</div>
<div class="field">
<%= label_tag "repeats" %>
<%= check_box_tag(:recurring) %>
</div>
<div class="field" id="recurring_fields" style="display:none">
<%= render 'recur' %>
</div>
<h3>Students</h3>
<div id="students">
<div class="items">
<%= f.nested_fields_for :appointments do |s| %>
<fieldset class="item">
<%= s.collection_select(:user_id, @students, :id, :students_name, :prompt => false) %>
<a href="#" class="remove">remove</a>
<%= s.hidden_field :_destroy %>
</fieldset>
<% end %>
</div>
<a href="#" class="add">Add Student</a>
</div>
<br>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
这一切都按计划进行 - 用户可以进行预订并将许多用户添加到预订中。
当我想使用约会模型的user对象时出现问题:
<%= appointment.user_id %>
上面的代码将 id 显示为一个整数,因此证明它被正确存储了但是
<%= appointment.user %>
出现空白??
我不明白为什么我确定关系设置正确?一直用这个把我的头发拉出来。有什么想法吗?
【问题讨论】:
标签: ruby-on-rails-4 associations belongs-to fields-for