在我们的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()。日历 –