Tôi có 3 mô hình: báo giá, khách hàng và mục. Mỗi trích dẫn có một khách hàng và một mục. Tôi muốn tạo một báo giá mới, một khách hàng mới và một mục mới trong các bảng tương ứng của họ khi tôi nhấn nút gửi. Tôi đã xem xét các câu hỏi và railscasts khác và hoặc là họ không làm việc cho tình hình của tôi hoặc tôi không biết làm thế nào để thực hiện chúng.Ruby on Rails: tạo bản ghi cho nhiều mô hình với một biểu mẫu và một biểu mẫu
quote.rb
class Quote < ActiveRecord::Base
attr_accessible :quote_number
has_one :customer
has_one :item
end
customer.rb
class Customer < ActiveRecord::Base
attr_accessible :firstname, :lastname
#unsure of what to put here
#a customer can have multiple quotes, so would i use has_many or belongs_to?
belongs_to :quote
end
item.rb
class Item < ActiveRecord::Base
attr_accessible :name, :description
#also unsure about this
#each item can also be in multiple quotes
belongs_to :quote
quotes_controller.rb
class QuotesController < ApplicationController
def index
@quote = Quote.new
@customer = Customer.new
@item = item.new
end
def create
@quote = Quote.new(params[:quote])
@quote.save
@customer = Customer.new(params[:customer])
@customer.save
@item = Item.new(params[:item])
@item.save
end
end
items_controller.rb
class ItemsController < ApplicationController
def index
end
def new
@item = Item.new
end
def create
@item = Item.new(params[:item])
@item.save
end
end
customers_controller.rb
class CustomersController < ApplicationController
def index
end
def new
@customer = Customer.new
end
def create
@customer = Customer.new(params[:customer])
@customer.save
end
end
hình thức của tôi cho báo giá/new.html.erb
<%= form_for @quote do |f| %>
<%= f.fields_for @customer do |builder| %>
<%= label_tag :firstname %>
<%= builder.text_field :firstname %>
<%= label_tag :lastname %>
<%= builder.text_field :lastname %>
<% end %>
<%= f.fields_for @item do |builder| %>
<%= label_tag :name %>
<%= builder.text_field :name %>
<%= label_tag :description %>
<%= builder.text_field :description %>
<% end %>
<%= label_tag :quote_number %>
<%= f.text_field :quote_number %>
<%= f.submit %>
<% end %>
Khi tôi cố gắng trình mà tôi nhận được một lỗi:
Can't mass-assign protected attributes: item, customer
Vì vậy, để thử và sửa chữa nó tôi cập nhật các attr_accessible trong quote.rb bao gồm: mục,: khách hàng nhưng sau đó tôi nhận được lỗi này:
Item(#) expected, got ActiveSupport::HashWithIndifferentAccess(#)
Bất kỳ trợ giúp sẽ được đánh giá rất nhiều.
Hãy thử tạo: tên và: mô tả có thể truy cập và: firstname và: lastname có thể truy cập trong các mô hình tương ứng của chúng. – lilwupster
@lilwupster Tôi đã làm điều đó nhưng tôi vẫn nhận được các lỗi tương tự. – notblakeshelton