Вопрос

I have two objects: Surveys and Questions. They are set up in a HABTM relationship such that surveys can have multiple questions and questions can belong to multiple surveys.

I am very new to Ruby on Rails, but have extensive experience with CakePHP. I was wondering what the proper way to relate questions to surveys in rails.

When I am POSTing to "surveys" the controller's create method is invoked, and from the scaffolding I created, I am able to create a basic survey object. What I am trying to do now is pass in an array of Question_IDs so that they can be automagically related to each other by the ActiveRecords Association.

here is my migration:

class CreateJoinTableQuestionSurvey < ActiveRecord::Migration
  def change
    create_join_table :questions, :surveys do |t|
      # t.index [:question_id, :survey_id]
      # t.index [:survey_id, :question_id]
    end
  end
end

For cakePHP, I would take an approach of going through each element in the array and creating a new Question_Survey object, manually assigning the values for the Question_ID and Survey_ID properties, and saving it to the database. Is the correct (as the designers intended) way to do it in Rails? If not, how would you create an object and an association at the same time?

Это было полезно?

Решение

This step by step procedure will help you to understand. This example is written for rails version <= 3.2. You can also see the Railscast video tutorial as you are making question & answer(checkboxes may be needed) app.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top