-2

I have an API that returns info straight from the database and noticed Rails is storing a utf8 check mark and the authenticity token. What is the best way to remove this before it is saved?

{"achievements":[{"utf8":"✓","authenticity_token":"XDzrmNqNyt6OfhWpAzu3j7LhMd/sRcr/4oLsPxRMrDY=","achievement":"Big Guns",...

An example of the controller code:

def achievements
  if params.include?(:ach)
    @achievement = Achievement.new(params[:ach])
    if @achievement.save
      redirect_to action: :achievements and return
    end
  end
end

Example of the view:

<%= form_tag '', multipart: true do %>
<div class="four columns">Name <input name="ach[achievement]" type="text" ></div>
<div class="five columns">Description <input name="ach[description]" type="text" ></div>
<% end %>
Eddie
  • 1,119
  • 10
  • 21

3 Answers3

4

Rather than try to write up a long post, I'll just note 3 things that should get you headed in the right direction. If it's confusing, comment and I'll explain further:

  1. The utf8=✓ is inserted into your HTML when you use the form helpers in Rails.
  2. You should not be handing the entire params object to your model.
  3. You should always build your JSON API responses from known-safe attributes.
coreyward
  • 68,091
  • 16
  • 122
  • 142
  • Thanks for answering, So while saving I should put in each individual parameter or is there a way to check that extra stuff isn't being saved? – Eddie Apr 16 '15 at 21:14
  • I'm confused because there isn't an authenticity_token field in the model. – Eddie Apr 16 '15 at 21:22
  • @Eddie I don't know what your code is doing because you haven't shared it here. For controlling what you pass to your model: http://guides.rubyonrails.org/action_controller_overview.html#strong-parameters and for your question about the `authenticity_token`, see: http://stackoverflow.com/questions/941594/understand-rails-authenticity-token – coreyward Apr 16 '15 at 22:44
  • I added some example code but it seems like you already understand what I was doing by your response. – Eddie Apr 17 '15 at 15:37
  • That `mongoid` tag explains a lot. ;) – coreyward Apr 17 '15 at 16:09
1

You can remove the key-pair from the params hash, by using in the reject method in the Hash class.

Example:

hash.reject! {|k,_| k.to_s.eql?("utf8") || k.to_s.eql?("authenticity_token") }
the Tin Man
  • 150,910
  • 39
  • 198
  • 279
Tucker
  • 659
  • 4
  • 16
0

Dynamic fields must be enabled in the configuration.

As mentioned by coreyward, params should be selectively added to model, in this case.

This is what ended working best for me:

achievement_params = %w[achievement description]
@achievement = Achievement.new(params.select { |key,_| achievement_params.include? key })
Eddie
  • 1,119
  • 10
  • 21
  • I haven't tested this but it might be a better way to do the same thing achievement = Achievement.new achievement.attributes = params – Eddie Apr 30 '15 at 14:44