0
def class Question < ActiveRecord::Base
    has_many :answers
    has_one :user_answer, -> (uid) { where(user_id: uid) }
end

@question = Question.find(5)
@question.to_json(:include => user_answer(2) )

In the above example I have an association that expects a parameter. How can I include this association in a json include with the parameter?

I have solved the issue using an instance variable, but it's annoying. I'd like to find a better solution. This is not the same example, but a simpler one.

1 Answer 1

1

You should use a scope instead of the has_one:

def class Question < ActiveRecord::Base
  has_many :answers
  scope :user_answers, -> (uid) { where(user_id: uid) }
end

@questions = Question.user_answers(user_id).limit(5)
@questions = @questions.to_json
Sign up to request clarification or add additional context in comments.

1 Comment

My use case is more complex. There are nested associations and I wanted to pass parameters to an association of and association. I should have used the more complex example. This answer is correct for this example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.