ruby - Rails 4 has_many :through w/ check_box_tag - only one side of associate being saved to join table -


i'm new rails , i've been trying extend michael hartl's tutorial in various ways. 1 of model user interests using has_many :through association. have following models set up:

class interest < activerecord::base     has_many :user_interests, dependent: :destroy     has_many :users, through: :user_interests end  class user < activerecord::base     has_many :user_interests, dependent: :destroy     has_many :interests, through: :user_interests end  class userinterest < activerecord::base     belongs_to :user         belongs_to :interest end 

my user_interests controller:

def index end  def create     @user_interest = current_user.user_interests.build(params[:interest_ids])     if @user_interest.save         redirect_to current_user         flash[:success] = "interests updated!"     else         render 'index'     end end  def destroy     @user_interest = userinterest.find(params[:user_id][:interest_ids])     current_user.user_interests(@user_interest).destroy end 

the view:

<%= form_for(current_user.user_interests.build(params[:interest_ids])) |f| %>     <%= hidden_field_tag "user[interest_ids][]", nil %>     <% interest.all.each |interest| %>         <%= check_box_tag "user[interest_ids][]", interest.id, current_user.interest_ids.include?(interest.id), id: dom_id(interest) %>         <%= label_tag dom_id(interest), interest.activity %><br>     <% end %>     <%= f.submit "update interests", class: "btn btn-large btn-primary" %> <% end %> 

when run app can select check box , click submit button user id saved in user_interests table. like:

id integer    user_id    interest_id    created_at_timestamp    updated_at_timestamp     1           2155                      2014-04-06 ect...       2014-04-06 ect... 

at first trying use users controller create association, causing issues because didn't have interests check boxes displayed on users#edit action, wanted them have own page. need interest ids save user_interests table along user id?

please have try following code.

def create    interests = interest.where(id: params[:user][:interest_ids])    current_user.interests.push(interests)    flash[:success] = "interests updated!"    redirect_to current_user end 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -