vendredi 29 mai 2015

Adding a column Migration with a default value in ruby on rails

I am using SQLite3 and I would like the following to work:

class AddNameToGoal < ActiveRecord::Migration
  def change
    add_column :goals, :goal_name, :text, default: goal.exercise.name
  end
end

How do I get the above to work.

I doubt it will work as it is but that's what I want.

Specifically, The user is associated with an Exercise through the exercise_id column.

belongs_to :user
belongs_to :exercise
has_many :workouts, dependent: :destroy

(This is the model for Goal)...

I would like the user to be able to choose their own name for the Goal but I can give them the hint to name the goal after the Exercise's name and if they choose to leave it blank it will default to the exercise's name. More importantly this must happen on the SQL side so that later when I have a collection drop down which requires a name of the goal they will need a name which corresponds to the exercise.

<%= f.collection_select(:goal_id, @goals, :id, 
:goal_name, :include_blank => "Please Select") %>

The Exercise Model is made in Rails to have id, Name, other columns.

Exercise Model:

class Exercise < ActiveRecord::Base
    has_one :goal

Is there a strategy by which that is possible.

Another option would be to help me find a strategy for active record so that I can do:

<%= f.collection_select(:goal_id, @goals, :id, 
:goal_name, :include_blank => "Please Select") %>

with (something else to replace goal_name with Exercise.name like goal.exercise.name and goal.id and show only the ID.

Aucun commentaire:

Enregistrer un commentaire