来自关系的联合数据

时间:2014-04-05 20:22:00

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我在Rails4应用程序中使用了很多关系因为stackoverflow用户的许多答案都比HABTM更多。不幸的是,我无法弄清楚如何从我的连接模型(称为"参与")视图页面调用关系数据。我有3个问题:

1.在app / views / participations / show.html.erb

我想拨打这样的电话,以便返回在exam_centers表格下保留的首选考试中心城市字段:

<%= @participation.exam_center_preference %>

但它只返回身份证。我需要获取exam_center&#34; city&#34;带有此ID号的字段。

2.在app / views / participations / index.html.erb

我需要在show.html.erb

中做同样的事情
<%= participation.examination.bookings %>

第3。在app / views / participations / _form_html.erb

我不知道如何在参与模型的表单部分中调用exam_centers模型中的数据。当我使用这样的东西时;

<%= f.input :exam_center_preference, collection:Booking.where(examination_id: @examination.id), label: 'Choose', label_method: :id %>

它返回了相关考试中心的ID - 但我还需要&#34; city&#34; ExamCenter模型中的值为label_method。

请参阅下面的collection和label_method:

<%= simple_form_for([@examination, @participation]) do |f| %>
  <%= f.input :exam_center_preference, collection:HOW?, label: 'Choose', label_method: HOW? %>
  <%= f.button :submit, "Save", :class => 'btn btn-large btn-warning' %>
<% end %>

提前致谢。

这是我的模型结构:

examination.rb:

class Examination < ActiveRecord::Base
  has_many :participations
  has_many :users, :through => :participations

  has_many :bookings
  has_many :exam_centers, :through => :bookings
end

participation.rb:

class Participation < ActiveRecord::Base
  belongs_to :user
  belongs_to :examination
end

user.rb

class User < ActiveRecord::Base
  foo-bar
end

正如您所看到的,我正在参与&#34;参与&#34;作为考试和用户模型之间的连接模型。

我也在考试和考试中心之间建立了这种关系&#34; Booking&#34;加入模型。这是结构=&gt;

examination.rb

class Examination < ActiveRecord::Base
  you-can-see-above
end

booking.rb

class Booking < ActiveRecord::Base
  belongs_to :examination
  belongs_to :exam_center
end

exam_center.rb

class ExamCenter < ActiveRecord::Base
  has_many :bookings
  has_many :examinations, :through => :bookings
end

* 架构结构=&gt; *

  create_table "examinations", force: true do |t|
    t.string   "name"
    t.string   "shortname"
    t.datetime "exam_date"
  end

  create_table "participations", force: true do |t|
    t.integer  "user_id"
    t.integer  "examination_id"
    t.boolean  "payment_status"
    t.string   "language_preference"
    t.string   "exam_center_preference"
  end

  create_table "bookings", force: true do |t|
    t.integer  "examination_id"
    t.integer  "exam_center_id"
  end

  create_table "exam_centers", force: true do |t|
    t.string   "country"
    t.string   "city"
    t.string   "building"
    t.text     "address"
  end

路线=&gt;

resources :exam_statuses, :exam_centers, :exam_fees
resources :examinations do
  resources :participations do
    member do
      get :update_profile_information
      get :approve_application
    end
  end
end

0 个答案:

没有答案