更改多对多关系表中的字段

时间:2014-04-26 01:56:28

标签: ruby-on-rails ruby

你好,我很难调试我的代码。我需要做的是创建一个页面,用户将键入姓氏,系统将返回与之相关的信息。我已经有两个字段在最后一个字段中正常工作但是给我带来了麻烦。最后一个字段最初来自房间表,但现在我需要将其更改为费率表。我不确定我需要将哪些文件更改为房间如果有人可以帮助我我会很感激!

首先输出页面需要更改

<%= booking.room.description %> 

<%= booking.rate.cost %>

(我得到一个未定义的方法`room')

<h1>Bookin#bookout</h1>
<p>Find me in app/views/bookin/bookout.html.erb</p>

 <center><table width = 65% border = 1> 
 <tr> <th> Customer Name</th><th> Room Number </th>  <th> Cost </th></tr>   
   <% @customer_list.each do |customer| %> 
<% customer.bookings.each do |booking| %> 
<tr> 
<td> <%= customer.last %> </td> 
<td> <%= booking.apple.roomnumber %> </td> 
<td> <%= booking.room.room_level %> </td> 
</tr> 
<% end %> 
<% end %>

  </table>
  </center>

这是客户模型

class Customer < ActiveRecord::Base
  attr_accessible :address, :city, :country, :course, :first, :last, :state, :takerint, :zip

  validates :address, :city, :country, :first, :last, :course, :state, :takerint, :zip, presence: true

  has_one :account
  has_many :courses, :through => :registrations
  has_many :registrations

  def takersvsint
   "#{first} - #{last} - #{takerint}"
  end



end

这是预订模式

class Booking < ActiveRecord::Base 


  belongs_to :apple 
  belongs_to :customer 
  belongs_to :rate

end

这是苹果模型

class Apple < ActiveRecord::Base

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

这是费率模型

class Rate < ActiveRecord::Base

 validates :season, :room, :cost, presence: true 

 has_many :bookings
 has_many :customers, :through => :bookings

end

我认为问题出在我的架构中,但我不知道如何更改它。应该没有room_id

create_table "bookings", force: true do |t|
    t.integer  "customer_id", null: false
    t.integer  "room_id",     null: false
    t.integer  "apple_id",    null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "bookings", ["apple_id"], name: "index_bookings_on_apple_id"
  add_index "bookings", ["customer_id"], name: "index_bookings_on_customer_id"
  add_index "bookings", ["room_id"], name: "index_bookings_on_room_id"

2 个答案:

答案 0 :(得分:0)

生成迁移为: -

rails generate migration AddRateIdToBookings rate_id:integer

将生成

class AddRateIdToBookings < ActiveRecord::Migration
  def change
    add_column :bookings, :rate_id, :integer
  end
end

在运行migartion

之前运行migartion或自定义它

答案 1 :(得分:0)

生成迁移以在rates表中添加对bookings的引用,如下所示:

rails generate migration AddRateRefToBookings rate:references

这将生成如下迁移:

class AddRateRefToBookings < ActiveRecord::Migration
  def change
    add_reference :bookings, :rate, index: true
    remove_reference :bookings, :room, index: true   ## Add this line in migration
  end
end

按照上面的建议在迁移中添加remove_reference :bookings, :room, index: true行,从room_id表中删除引用bookings

此次运行后rake db:migrate