获得"无法写出未知属性"当试图保存has_many关联

时间:2016-11-16 20:11:56

标签: ruby-on-rails model ruby-on-rails-5 has-many

我正在使用Rails 5.我有两个相互关联的模型......

class Scenario < ApplicationRecord
  belongs_to :grading_rubric, optional: true
  has_many :confidential_memo
  has_many :roles

  attr_accessor :roles_str
end 

class Role < ApplicationRecord
  belongs_to :scenario
end

我有这张表与两人有关......

sims=> \d scenario_roles
                                  Table "public.scenario_roles"
   Column    |            Type             |                          Modifiers                          
-------------+-----------------------------+-------------------------------------------------------------
 id          | integer                     | not null default nextval('scenario_roles_id_seq'::regclass)
 scenario_id | integer                     | 
 role_id     | integer                     | 
 created_at  | timestamp without time zone | not null
 updated_at  | timestamp without time zone | not null

但是,当我尝试在控制器中创建和保存内容时,我遇到了问题。这就是我正在做的事情

  def create
    @scenario = Scenario.new(scenario_params)
    # Define the roles for this scenario
    role_names = @scenario.roles_str.split("\n")
    roles = []
    role_names.each do |role|
      role_obj = Role.new({:name => role, :scenario => @scenario})
      if role_obj.save!
        roles.push(role_obj)
      end
    end
    @scenario.roles = roles
    respond_to do |format|
      if @scenario.save

我收到错误,“无法写出未知属性scenario_id”行“role_obj = Role.new({:name =&gt; role,:scenario =&gt; @scenario })”。我做错了什么?

0 个答案:

没有答案