Check a field is contains in another list in ROR

对着背影说爱祢 提交于 2019-12-13 08:03:10

问题


I have a list called @domianskill_technical_skills. This table is related table for domain_skills and technical_skills data and is retrieved based on domain_skill_id

I need return all technical_skills from the technical_skills table but have one more attribute named assigned which is true if the technical_skill_id is present in the @domianskill_technical_skills list.

My working code is like below

def assigned_technical_skills

      @domain_skill_technical_skills = DomainSkillsTechnicalSkill.select('id, technical_skill_id').where(domain_skill_id: params[:domain_skill_id])

      Rails.logger.info(@domain_skill_technical_skills.to_a)

      TechnicalSkill.all.where(record_status: 1).each do |skill|

        if @domain_skill_technical_skills.include?(skill.id) then
          Rails.logger.info(skill.id.to_s + skill.name)
        end

      end

      respond_with @domain_skill_technical_skills
  end

Please guide me to correct the if statement and also need to select the needed fields (id, name, assigned) and create one instance for return.


回答1:


You might want to replace your code with this, if DomainSkillsTechnicalSkill has 'technical_skill_id' column

def assigned_technical_skills
  # just collect technical_skill_id 
  @domain_skill_technical_skill_ids = DomainSkillsTechnicalSkill.select('id, technical_skill_id').where(domain_skill_id: params[:domain_skill_id]).collect(&:technical_skill_id)
  Rails.logger.info(@domain_skill_technical_skill_ids.to_a)
  @technical_skills = []  
  TechnicalSkill.select('id, name').where(record_status: 1).each do |skill|

    @technical_skills << skill.as_json.merge!(
      { assigned: @domain_skill_technical_skill_ids.include?(skill.id)}
    )       
  end
  respond_with @technical_skills
end


来源:https://stackoverflow.com/questions/29817975/check-a-field-is-contains-in-another-list-in-ror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!