0

On hyperstack, Assignment#destroy method fails with "Bad request" only on the first trial, where the Assignment is a model through which "has_many" relationship is made. The #destroy succeeds on the second trial.

I have installed the rails-hyperstack gem of 'edge' branch.

I am trying to make a many to many relationship between Issue and Agent models through Assignment model as below :

class Assignment < ApplicationRecord
  belongs_to :agent
  belongs_to :issue
end
class Issue < ApplicationRecord
  has_many :assignments, foreign_key: :issue_id
  has_many :agents, through: :assignments
end
class Agent < ApplicationRecord
  has_many :assignments, foreign_key: :agent_id
  has_many :issues, through: :assignments

  def deassign(number)
    issue = issues.find_by(number: number)
    assignments.find_by(issue_id: issue.id).destroy.then do |result|
      if result[:success]
        issues.delete(issue)
        return true 
      end
      puts "deassign failed #{result[:message]}"
      return false
    end
  end
end
class Main < HyperComponent

  before_mount do
    @agent = Agent.first
  end

  render(UL) do
    @agent.issues.pluck(:number).each do |num|
      LI { num.to_s }
      .on(:click) do
        @agent.deassign(num)
      end
    end
  end
end

Issue numbers are listed on the page.

When a number is clicked, Agent#deassign(number) is called, and it calls Assignment#destroy. This way, I am trying to delete the association on the hyperstack, because issues.delete(issue).save can't be used in this case.

Assignment#destroy fails only on the first time when the number is clicked. It succeeds on the second time, and the relationship is deleted successfully.

The error and the call stack displayed in the chrome developer console when the #destroy fails :

http.rb:193 POST http://localhost:5040/hyperstack/execute_remote 400 (Bad Request)
send    @   http.rb:193
post    @   http.rb:126
run @   server_op.rb:14
destroy @   isomorphic_base.rb:560
Opal.send   @   runtime.self-a59b728…763d.js?body=1:1605
destroy @   instance_methods.rb:161
deassign    @   agent.rb:7
KoyaChan
  • 3
  • 3
  • Hi @koyaChan - this is an excellent question, well laid out and well asked. I don't have an easy solution for you, but just a suggestion that you can abstract complex database operations into a `server_method` which will only operate on the server, hence all the back and forth required between the client and server in this complex relationship. I am hoping someone else will give you a better answer though. – BarrieH Sep 15 '19 at 07:39
  • Finally this issue was resolved by using ServerOp as advised from adamcreekroad and [BarrieH](https://stackoverflow.com/users/5308751/barrieh) in the [hyperstack slack thread](https://app.slack.com/client/THRP7BEA2/CHFJ8AR5X/thread/CHFJ8AR5X-1568533199.009600). – KoyaChan Oct 03 '19 at 09:53

0 Answers0