anndrew78
anndrew78

Reputation: 196

How to get serialized attribute in rails?

I have serialized column of Post model

serialize :user_ids 

after save I can see in my console:

> p = Post.last

 => #<Post id: 30, title: "almost done2", created_at: "2017-05-08 15:09:40", updated_at: "2017-05-08 15:09:40", attachment: "LOGO_white.jpg", user_ids: [1, 2]> 

I have permitted params :user_ids at my controller

def post_params
  params.require(:post).permit(:title, :attachment, :user_ids)
end

All I need is to store @user_ids and copy to other model as atrribute, but can't get instance like @user_ids = @Post.last.user_ids

Get error

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.post_id: SELECT "users".id FROM "users" WHERE "users"."post_id" = ?

Thanks for help!

Upvotes: 0

Views: 768

Answers (1)

TomD
TomD

Reputation: 791

I think you've chosen really wrong name for your serialized attribute, unfortunately!

See, Rails is trying to be helpful and relation_ids method is allowing you to call ids of all related object. Consider those two models

class User
  belongs_to :post
end

class Post
  has_many :users
end

You can call something like

Post.last.user_ids

Which will then try to find all users that belong to this post and give you back their ids.

Look at query that you get:

SELECT "users".id FROM "users" WHERE "users"."post_id" = ?

This is exactly what Rails is trying to do. Select USERS that belong to the post and give you their ids. However User does not have post_id column so this fails.

You're better off changing the name of your serialized column to something that won't confuse Rails. However, if you want to keep your column, you can override the method by putting this on the Post model

  def user_ids
    self[:user_ids]
  end

This is non-ideal however, but will leave it up for you to decide what to do. My preference would be column rename, really. Will save you a lot of headeache

Upvotes: 1

Related Questions