在我們的Rails應用程序,有3種型號:導軌的has_many:通過關聯:保存實例到連接表
class User < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :calendars, through: :administrations
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
class Calendar < ActiveRecord::Base
has_many :administrations, dependent: :destroy
has_many :users, through: :administrations
end
,這裏是相應的遷移:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.timestamps null: false
end
end
end
class CreateAdministrations < ActiveRecord::Migration
def change
create_table :administrations do |t|
t.references :user, index: true, foreign_key: true
t.references :calendar, index: true, foreign_key: true
t.string :role
t.timestamps null: false
end
end
end
class CreateCalendars < ActiveRecord::Migration
def change
create_table :calendars do |t|
t.string :name
t.timestamps null: false
end
end
end
我們創造了calendar#create
行動如下:
def create
@calendar = current_user.calendars.build(calendar_params)
if @calendar.save
flash[:success] = "Calendar created!"
redirect_to root_url
else
render 'static_pages/home'
end
end
和相應的_calendar_form.html.erb
部分:
<%= form_for(@calendar) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_field :name, placeholder: "Your new calendar name" %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>
這個「作品」,因爲,當我們通過表單創建一個新的日曆,它在Rails的控制檯顯示出來,當我們鍵入Calendar.all
。
但是,似乎沒有新的@administration
正在創建,並且管理表沒有更新,因爲當我們在控制檯中輸入Administration.all
時什麼也沒有返回。
我們認爲管理表是用戶表和日曆表之間的連接表,分別包含user_id
和calendar_id
列的管理表在創建新日曆時會自動更新。
我們該如何做到這一點?我們是否需要創建特定的administration#create
操作?
更新:根據的評論和答覆,我們採取了以下CalendarsController
:
class CalendarsController < ApplicationController
def create
@calendar = current_user.calendars.build(calendar_params)
if @calendar.save
current_user.administrations << @calendar
@calendar.administration.role = 'creator'
flash[:success] = "Calendar created!"
redirect_to root_url
else
render 'static_pages/home'
end
end
...
然而,這將返回以下錯誤:
ActiveRecord::AssociationTypeMismatch in CalendarsController#create
unless record.is_a?(reflection.klass) || record.is_a?(reflection.class_name.constantize)
message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
raise ActiveRecord::AssociationTypeMismatch, message
end
end
app/controllers/calendars_controller.rb:6:in `create'
難道我們失去了一些東西?
'User.find()。calendars'返回任何東西? –
Ojash
是的,它返回:SyntaxError:(irb):1:語法錯誤,意外的'<',期待')' User.find()。日曆 –