Join 2 tables with custom metadata in Rails
I have a User开发者_Python百科 model, and a Goal model. The Goal model has a name, and a type column, which has the following three records right now.
name | type
------------------------
Read Novels | Reading
Read Newspaper | Reading
Write Reviews | Writing
Now I want to provide each user, an interface to fill in the number of hours they spend on this activity every month (hours_per_month
), and the number of different days they do it (days_per_month
).
Ideally, I'd want to work with the data like
current_user = User.find(params[:id])
current_user.goals.each do |goal|
puts goal.name
puts goal.type
puts goal.hours_per_month
puts goal.days_per_month
end
How should I create this new table/model, that joins the Goals to User, and have access to the static Goal attributes, and the user filled values, like the code sample above?
You could create an Activity
model and give it a table definition like:
activities:
- user_id
- goal_id
- hours_per_month
- days_per_month
Then add to:
User
has_many :activities
has_many :goals, :through => :activity
Goal
has_many :activities
has_many :users, :through => :activity
Activity
belongs_to :user
belongs_to :goal
You can use a generator to do most of the work iirc.
Table goals_users
column: user_id
column: goal_id
column: hours_worked
Models:
User:
has_and_belongs_to_many :goals
Goals:
has_and_belongs_to_many :users
def hours_per_month
#calculate
end
def hours_per_day
#calculate
end
Obviously set up the additional columns outside the join however you like.
Additional
In any model using AR joins you'll need to access the intermediary record directly.
精彩评论