Ruby on Rails new() method not storing values

时间:2015-12-14 17:56:38

标签: ruby-on-rails ruby activerecord

I have a modified copy of https://github.com/talho/openphin/blob/master/app/controllers/admin/invitations_controller.rb

The main code is primarily the same, however our system was upgraded a few months back to Rails 4.x and the invitation system no longer works.

The method with the issue is create. I have tried swapping out:

@invitation = Invitation.new(params[:invitation])

with

@invitation = Invitation.create(invitation_params)

And creating

def invitation_params
    params.require(:invitation).permit!
end

However, here is what I have:

invitation_params = {"name":"Test","subject":"test","body":"test","organization_id":"","author_id":24448}

@invitation = {"id":null,"name":null,"body":null,"organization_id":null,"author_id":null,"subject":null,"created_at":null,"updated_at":null,"lock_version":0}

Also, if I use create!, then my output error is:

E, [2015-12-14T13:03:38.664099 #24385] ERROR -- : Validation failed: Author can't be blank (ActiveRecord::RecordInvalid)

I could use any guidance/help on why everything ends up as null.

1 个答案:

答案 0 :(得分:2)

You call return what leaved the method, before you call save! in the record. Furthermore you might want to read about Strong Parameters. You might want to change your code to:

@invitation = Invitation.new(
  params.require(:invitation).permit( 
    :name, :subject, :body, :organization_id, :author_id
  )
)
@invitation.save!

render :json => { :invitation => @invitation }.as_json
return

Please note that you usually do not need to call return in controller method. And when you call save! immediately after new then create! might be an better option:

def create
  invitation = Invitation.create!(invitation_params)
  render json: { invitation: invitation }.as_json
end

private

def invitation_params
  params.require(:invitation).permit( 
    :name, :subject, :body, :organization_id, :author_id
  )
end