gpt4 book ai didi

ruby-on-rails - "Can' t mass-assign protected attributes"with nested protected models

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:02 24 4
gpt4 key购买 nike

我正在尝试让这个嵌套模型正常工作。我已经尝试了所有形式的复数/单数,完全删除了 attr_accessible,谁知道还有什么。

餐厅.rb:

# == RESTAURANT MODEL
#
# Table name: restaurants
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#

class Restaurant < ActiveRecord::Base
attr_accessible :name, :job_attributes

has_many :jobs
has_many :users, :through => :jobs
has_many :positions

accepts_nested_attributes_for :jobs, :allow_destroy => true

validates :name, presence: true

end

工作.rb:

# == JOB MODEL
#
# Table name: jobs
#
# id :integer not null, primary key
# restaurant_id :integer
# shortname :string(255)
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#

class Job < ActiveRecord::Base
attr_accessible :restaurant_id, :shortname, :user_id

belongs_to :user
belongs_to :restaurant
has_many :shifts


validates :name, presence: false

end

restaurants_controller.rb:

class RestaurantsController < ApplicationController

before_filter :logged_in, only: [:new_restaurant]

def new
@restaurant = Restaurant.new
@user = current_user
end

def create
@restaurant = Restaurant.new(params[:restaurant])
if @restaurant.save
flash[:success] = "Restaurant created."
redirect_to welcome_path
end
end

end

新的.html.erb:

<% provide(:title, 'Restaurant') %>

<%= form_for @restaurant do |f| %>
<%= render 'shared/error_messages' %>

<%= f.label "Restaurant Name" %>
<%= f.text_field :name %>

<%= f.fields_for :job do |child_f| %>

<%= child_f.label "Nickname" %>
<%= child_f.text_field :shortname %>

<% end %>

<%= f.submit "Done", class: "btn btn-large btn-primary" %>

<% end %>

输出参数:

{"utf8"=>"✓",
"authenticity_token"=>"DjYvwkJeUhO06ds7bqshHsctS1M/Dth08rLlP2yQ7O0=",
"restaurant"=>{"name"=>"The Pink Door",
"job"=>{"shortname"=>"PD"}},
"commit"=>"Done"}

我收到的错误是:

ActiveModel::MassAssignmentSecurity::Error in RestaurantsController#create

Cant mass-assign protected attributes: job
Rails.root: /home/johnnyfive/Dropbox/Projects/sa

Application Trace | Framework Trace | Full Trace
app/controllers/restaurants_controller.rb:11:in `new'
app/controllers/restaurants_controller.rb:11:in `create'

有人任何知道如何让它工作吗?谢谢!

最佳答案

在 restaurant.rb 中:

应该是 attr_accessible :name, :jobs_attributes代替 attr_accessible :name, :job_attributes

关于ruby-on-rails - "Can' t mass-assign protected attributes"with nested protected models,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12380761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com