rails 表单模型的参数数量错误(给定 9,预期 0)

rails wrong number of arguments (given 9, expected 0) with form model

我正在使用this构建表单模型(我想创建一个Transaction和一个Address,地址必须属于交易)。我收到 rails wrong number of arguments (given 9, expected 0) 错误,但无法弄清楚原因。错误在控制器参数中,但我不确定为什么它期望为 0。我的表单模型如下所示:

class TransactionForm
 include ActiveModel::Model

 attr_accessor :sender_id, :recipient_id, :item_id, :asking_price, :amount, :sender_agreement, :name, :street, :street_2, :state, :zip_code, :phone_number


 validate :sender_id
 validate :recipient_id
 validate :item_id
 validate :asking_price
 validates :amount, presence: true
 validates :sender_agreement, presence: true
 validates :name, presence: true
 validates :street, presence: true
 validates :street_2, presence: true
 validates :state, presence: true
 validates :zip_code, presence: true
 validates :phone_number, presence: true

 def save
  if valid?
   address = create_address
   transaction = create_transaction(address)
  end
 end

 private
 def create_address
  Address.create(name: name, street: street, street_2: street_2, state: state, 
                                    zip_code: zip_code, phone_number: phone_number)
 end

 def create_transaction(address)
  Transaction.create(sender_id: sender_id, recipient_id: recipient_id, item_id: item_id, asking_price: asking_price, amount: amount, sender_agreement: sender_agreement, sender_signed_at: Time.now, address: address)
 end
end

我的控制器的 #show#create 操作和白名单参数如下所示:

#this action is in a separate ItemsController, tho that doesn't really matter
def show
 @transaction = TransactionForm.new
end

#this action is in TransactionsController
def create
 @transaction = TransactionForm.new(transaction_params)
 if @transaction.save
  redirect_to item_path(@transaction.item), notice: "approved"
 else
  redirect_to item_path(@transaction.item), notice: "error"
 end
end

def transaction_params
 params.require(:transaction_form).permit!(:amount, :asking_price, :sender_agreement, :name, :street, :street_2, :state, :zip_code, :phone_number)
end

我的表格基本上是这样的:

<%= form_for @transaction, url: transactions_path do |f| %>
 <%= f.hidden_field :sender_id, value: current_user.id %>
 <%= f.hidden_field :recipient_id, value: @item.owner.id %>
 <%= f.hidden_field :item_id, value: @item.id %>
 <%= f.hidden_field :asking_price, value: @item.price %>
 <%= f.text_field :amount %>
 <%= f.text_field :name %>
 <%= f.text_field :street %>
 <%= f.text_field :street_2 %>
 <%= f.text_field :state %>
 <%= f.text_field :zip_code %>
 <%= f.text_field :phone_number %>
 <%= f.check_box :agreement %>
 <%= f.submit "submit" %>
<% end %>

这看起来或多或少与博客 [​​=28=] 中的代码完全相同,但出于某种原因,它需要 0 个参数。这是为什么?

params.permit! 将所有属性列入白名单 -> Rails permit!

你应该使用permit

您需要使用 permit 而不是 permit!。前者接受争论。后者没有。