Reputation: 153
I want to add relation between existing post and author.
I was trying to modify created_by
attribute but it's not accessible from object.
def set_author
if (@post.created_by.empty? && @post.author_code.present?)
if @post.author_code == params[:author_code]
@post.created_by = current_user
else
raise(ExceptionHandler::InvalidAuthorCode, Message.invalid_author_code)
end
else
raise(ExceptionHandler::DisallowedAction, Message.action_not_allowed)
end
end
It's not working because there is no method @post.created_by
even if it's present db.
Post model from schema.rb
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "content"
t.boolean "accepted", default: false
t.string "created_by"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "author_code"
end
Edit: part of post.rb
belongs_to :user, optional: true, foreign_key: :created_by
part of user.rb
has_many :confessions, foreign_key: :created_by
Upvotes: 0
Views: 58
Reputation: 153
I was trying to update @post attributes a wrong way. Changed
@post.created_by = current_user
to
@post.update_attribute(:created_by, current_user)
and it's working. It's not a Devise user model, just self written.
Upvotes: 0
Reputation: 3721
Assuming that it only fails for the @post
which don't have any created_by OR user
then you can use following:
@post.try(:created_by).blank? && @post.author_code.present?
Upvotes: 1