alt
alt

Reputation: 13907

Set a field value outside a form in Rails

So I have a Rails app with a Post model. One of the fields is collection_id.

Each post should have the ID of the latest collection at the time of posting. If I have that ID in the backend, and I remove the form field for collection_id, how can I make sure this ID goes into the database without having a hidden_field in the Rails frontend?

The problem with a hidden field is that users could use a web inspector to change the value. This needs to be secure.

What's the best way to do this?

Upvotes: 1

Views: 911

Answers (1)

Zippie
Zippie

Reputation: 6088

If you have that ID in your backend, you can pass it in your controllers action before saving:

   @post = Post.create(params[:post])
   @post.controller_id = variable_holding_the_id
   if @post.save ...

or in some cases you can do it in the model with a callback:

   after_create :set_collection_id

   def set_collection_id
      self.collection_id = variable_holding_the_id
   end

Upvotes: 4

Related Questions