خرید بک لینک

Vote count: 0

When a user creates an event, they are also creating an associated task, which can have many followers, but one follower must be the owner of the task. A task owner has the task_followers owner flag set to true. Here is the relationship:

class Event < ActiveRecord::Base
  belongs_to :task
end

class Task < ActiveRecord::Base
  has_one :event
  has_many :task_followers, dependent: :destroy
  has_many :followers, through: :task_followers, dependent: :destroy
  validate :owner_follower

  def owner_follower
    unless task_followers.where(owner: true).present?
      errors[:task_owner] << "must be present"
    end
  end
end

class User < ActiveRecord::Base
  has_many :task_followers, foreign_key: :follower_id
  has_many :tasks, through: :task_followers
end

class TaskFollower < ActiveRecord::Base
  belongs_to :follower, class_name: 'User', foreign_key: :follower_id
  belongs_to :task

  validates_uniqueness_of :task_id, scope: :follower_id
end

User gets to select task owner in a form:

 <%= form_for @event, remote: true, data: { type: :html } do |f| %>
  <%= f.fields_for :task, f.object.task do |task_builder| %>
    <%= task_builder.fields_for :task_followers, task_builder.object.task_followers.build do |task_follower_builder| %>
      <%= task_follower_builder.select :follower_id, User.all.collect {|user| [user.name, user.id, { 'data-associated-id' => user.id }] }, {include_blank: true}, {class: 'form-control'} %>
      <%= task_follower_builder.hidden_field :owner, value: true %>
    <% end %>
  <% end %>
 <% end %>

The following hash is sent to the server:

  params = {
    'event' => {
      'task_attributes' => {
        'task_followers_attributes' => {
          '0' => { 'follower_id' => 1, 'owner' => true }
        }
      }
    }
  }

So when the event is set, in tu the task is set, and in tu the task_followers collection has a follower added.

But I am confused by why present? retus false:

def owner_follower
  a_follower_exists = task_followers.first
  but_says_false = task_followers.where(owner: true).present?
  ...
end

The task_follower is there and its owner field is true, yet when I call present? on the association, it retus false. Why?

asked 1 min ago

برچسب: نویسنده: استخدام کار تاريخ: جمعه 28 خرداد 1395 ساعت: 7:20

صفحه بندی