Posts

Showing posts with the label activerecord

Nesting Comments Yii2

Image
Nesting Comments Yii2 I have a comment table, like below: +-----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | user_id | int(11) | NO | | NULL | | | parent_id | int(11) | NO | | 0 | | | post_id | int(11) | NO | | NULL | | | body | text | NO | | NULL | | | date | datetime | NO | | NULL | | | status | tinyint(1) | NO | | 0 | | +-----------+--------------+------+-----+---------+----------------+ Comment parent_id by defautl is 0, if comment is answered, parent id insert in parent_id column. And make a relation with User Table with below code: public function getPosts() { ...

Best way to save attribute inside save block?

Best way to save attribute inside save block? In my controllers I often have functionality like this: @account = Account.new(account_params) if @account.save if @account.guest? ... else AccountMailer.activation(@account).deliver_later @account.update_column(:activation_sent_at, Time.zone.now) flash[:success] = "We've sent you an email." redirect_to root_path end end What's the best way to send an email and update the activation_sent_at attribute without having to save the record twice? Calling update_column doesn't feel right to me here because AFAIK it creates an extra SQL query (correct me if I'm wrong). activation_sent_at update_column The workaround is using assign_attributes , but I would not recommend it. Your code is fine, and an additional update query to update the column shouldn't make much difference. Also, check like guest? can also be applicable on some model hooks which won't be in...