I'm using this to build a form model (i want to create a Transaction
and an Address
, and the address must belong to the transaction). I'm getting a rails wrong number of arguments (given 9, expected 0)
error, and cannot figure out why. The error is in the controller params, but I'm not sure why it's expecting 0. My form model looks like this:
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
And my controller's #show
and #create
actions and whitelisted params look like this:
#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
My form basically looks like this:
<%= 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 %>
This looks more or less exactly like the code in the blog post, but for some reason it's expecting 0 args. Why is this?
params.permit!
whitelists all attributes ->
Rails permit!
You should use permit