简体   繁体   中英

how do I override create action with variables generated inside the controller in rails 4

This is the code that I have written in the create action of Payments Controller.

user_id=Performer.find_by_first_name(params[:payment][:first_name]).user.id
email=Performer.find_by_first_name(params[:payment][:first_name]).user.email
@payment = Payment.new(user_id,params[:payment][:desc],params[:payment][:amount],email,params[:first_name])
#@payment = Payment.new(payment_params)

When I try this I get the following error:

wrong number of arguments (5 for 0..1)

I cannot just pass the values of as such so I need to change them before I save it in the table. How do I do this?

It only accepts an hash of attributes:

@payment = Payment.new(
  user_id: user_id,
  desc: params[:payment][:desc],
  amount: params[:payment][:amount],
  email: email,
  first_name: params[:first_name]
)

Since you are using Rails 4 , I encourage you to take a look at strong_parameters .

Changing the values before saving them in the db

You can either use a before_save callback or defining custom accessors.

1. Using before_save callbacks:

If you want to change the values before saving them in the database, you can use a before_save callback:

class Payment < ActiveRecord::Base
  before_save :change_values

private

  def change_values
    self.amount = amount.do_something
    # etc.
  end
end

API documentation:

2. Using custom accessor:

Or you can define custom accessor:

2.1 With read_attribute and write_attribute

def amount=(dollars)
  write_attribute :amount, dollars.do_something
end

def amount
  read_attribute(:amount).do_something
end

API documentation:

2.2 With virtual attributes:

def amount_in_dollars
  amount.do_something
end

def amount_in_dollars=(dollars)
  self.amount = dollars.do_something
end

Railscasts:

 @payment = Payment.new(:column_1 => value/params[:],:column_2 => params[:desc])

if it is a form submit

@payment = Payment.new(param[:payment])

out side form submit

@payment.column_1 = value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM