开发者

working with select boxes (RoR)

I created an application in Rails and generated two models, one for students and one for awards.

rails students

script/generate scaffold student given_name:string middle_name:string family_name:string date_of_birth:date grade_point_average:decimal start_date:date

script/generate scaffold award name:string year:integer student_id:integer

Each student can have many 开发者_如何学Cawards, so I added has_many :awards to the student model. I also added a select box to the view that lets the user create new awards:

<%= f.select :student_id, Student.find(:all).collect {|s| [s.name, s.id]} %>

My question: If I wanted to give the user the option to create an award without specifying a student, how would I modify the select box to allow them to do this?

I'm brand new to Rails. Thanks!


What you're describing is a many to many relationship. What you've done is just a one to many relationship.

In a many to many relationship, you define many independent records on each side and use a join table to create links from one to another.

In a one to many relationship, each record on the one side is independent while each record on the many side is dependent on the one that it is linked to.

Examples stemming from your questions:

many to many: Each Student can have many awards, but do not need to be linked to an award to have meaning. Each award can be earned by many students, but do not need to be linked to an student to have meaning. StackOverflow's badges are a perfect example of this.

one to many: Each student can have many awards but do not need to be linked to an award to have meaning. Each award is unique to only one student.

How to turn your relationship to a many to many relationship:

  1. create an awardings table that has student_id and award_id columns.
  2. remove the student_id column from the awards table.
  3. Inform ActiveRecord of the relationships.

    class Student < ActiveRecord::Base
      has_many :awardings
      has_many :awards, :through => :awardings
      ...
    end
    
    class Awarding < ActiveRecord::Base
      belongs_to :student
      belongs_to :award
    end
    
    class Award < ActiveRecord::Base
      has_many :awardings
      has_many :students, :through => :awardings
    end
    
  4. Update your forms to reflect the changes.

    Use either a multple select box, or a series of checkboxes to manage many at once. There are many tutorials out there about this. This Railscast episode is way out of date but is a good start.

P.S. Your more likely to get answers if you don't check the community wiki box. Community wikis are for non-technical questions, where the answers are likely to be improved by several users.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜