Co2
Co2

Reputation: 353

RoR: How to populate table from radio buttons?

In my application I have a form with radio buttons:

<%= form_for @homework.homework_students.homework_ratings do |f| %>
  <label>
    <%= f.radio_button :fb_value, '1', :fb_type, 'Difficulty' %>
  </label>
  1
  <label>
    <%= f.radio_button :fb_value, '2', :fb_type, 'Difficulty' %>
  </label>
  2
  <label>
    <%= f.radio_button :fb_value, '3', :fb_type, 'Difficulty' %>
    3
  </label>
<%= f.button :submit %>
<% end %>

The aim is to populate two columns (called "value" and "type") for each homework in a table (not sure if syntax is correct above) called "homework_ratings" which is associated with a table called "homework_students":

homework_ratings.rb

belongs_to :homework_student, :class_name => 'HomeworkStudent', :foreign_key => :homework_student_id

homework_students.rb

 has_many :homework_ratings, :class_name => 'HomeworkRating'
    belongs_to :homework, :class_name => 'Homework', :foreign_key =>        :homework_id, dependent: :destroy

homework_students has many homeworks:

homework.rb

has_many :homework_students, :class_name => 'HomeworkStudent', dependent: :destroy

homework_ratings table:

id                  :integer          not null, primary key
#  homework_student_id :integer
#  type                :integer
#  value               :string(255)
#  created_at          :datetime         not null
#  updated_at          :datetime         not null

homeworks_controller.rb

def show
        @homework_ratings = HomeworkRating.all
...
end

In a nutshell i'm trying to populate a table from homeworks that has no direct association with homework but is indirectly associated as above through homework_students.

I get the error "undefined method homework_ratings" on trying to load page.

Any thoughts as to how best to approach this?

Thanks, can provide more info...

Upvotes: 0

Views: 51

Answers (1)

court3nay
court3nay

Reputation: 2365

Simplify. You're trying to record a rating for a piece of homework, right? so you create a dedicated ratings controller, and you just create a rating. Always try to make a resource out of something you're creating. You should have a lot of resources/controllers in your app.

<%= form_for @homework_rating do |f| %>
  <%= f.hidden_field :homework_student_id %>

in the controller:

def new
  @homework_student = HomeworkStudent.find params[:homework_student_id]
  @homework_rating = @homework.ratings.new
end

you probably also want to look as has_many :through

edit: you can't set two values with one radio button. but you can create a writer method in the ratings model

def set_values=(val)
  self.type = "foo"
  self.value = "bar"
end

you can then do all sorts of ruby on the val, like if or case. you'd need to come up with a way of communicating that between the radio buttons and the model action.

Upvotes: 1

Related Questions