0

How to handle tag_ids in post params to save it in related model? I would like to use for it only post_params method.

has_many :tags

def post_params
  params.require(:post).permit(:title, :message, :tag_ids)
end

#Parameters: {"post"=>{"title"=>"asdf", "message"=>"asfd", "tag_ids"=>"543d727a4261729ecd000000,543d8a914261729ecd010000"}}

I've got:

Mongoid::Errors::InvalidValue -
Problem:
  Value of type String cannot be written to a field of type Array

I found solution but I don't like it, in Post model I've added:

def tag_ids=str
  str.split(',').each do |id|
    t = Tag.find(id)
    self.tags << t
  end
end
luzny
  • 2,380
  • 7
  • 30
  • 64

2 Answers2

0

I think that you have to modify the incoming data in tag_ids in create action in your controller.

So when you receive the data, before you are saving the data into DB by, for example: post.create! you should add parsing to your PostsController action create:

If you want array of string:

post.tag_ids = params[tag_ids]split(",")

or if you want array of integers:

post.tag_ids = params[tag_ids]split(",").map(&:to_i)
Tom Hert
  • 947
  • 2
  • 10
  • 32
0

Something like this? (I'm assuming you want an array of ObjectId)

id_array = params['post']['tag_ids'].split(',').map { |id| BSON::ObjectId.from_string(id) }
params['post']['tag_ids'] = id_array
August
  • 12,410
  • 3
  • 35
  • 51