Tack
Tack

Reputation: 121

How to pass objects of one model to another in an index view?

I'm working with the Hartl Rails tutorial, adapting it to build a simple forum. Thanks to the tutorial, I have working User model/controller/views that allow for logging in and out and tracking the current user. I also have a "Topic" model which represents different topics of interest. The User model is set up so that each user has_many Topics.

I currently list 50 Topics in my topics index view and want to display a check box or button beside each topic, so that users can click and subscribe to the topic.

I've looked for hours and can't figure out how to use check boxes to add a checked topic to a user's list of topics. I apologize for the broad question, this was my last resort.

This is what the Topic and User Schema look like:

create_table "topics", force: :cascade do |t|
    t.string   "topic_name"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_topics_on_user_id"
end



create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.string   "password_digest"
    t.index ["email"], name: "index_users_on_email", unique: true
  end

I am not sure what else to include for this question. I will be watching attentively to provide any more necessary information.

Upvotes: 0

Views: 28

Answers (1)

vinyl
vinyl

Reputation: 569

I think what you’re looking for is a has_many_through association. Basically you’d want to create a third model UserTopics and when you submit your form you would create a new instance of a UserTopic for each selected checkbox. There’s some more info about this here:

https://guides.rubyonrails.org/association_basics.html

Upvotes: 1

Related Questions