Read the great update for the latest information.
Hello everybody,
I have a many-to-many relationship in a rails application that includes three tables: a user table, an interest table, and a join user_interests table, which also has a rating value, so the user can rate each of their interests on a scale of 1- 10.
Basically, I am looking for a way for a new user to create their rating when they subscribe and edit them in the future, as well as any information about their profile at the same time.
I tried to execute this question Rails nested form with has_many: through how to edit the attributes of the join model? , but the problem I am facing is trying to enable select a list in the mix and have several interests to evaluate for the user.
Model Code:
user.rb
has_many :user_interests, :dependent => :destroy
has_many :interests, :through => :user_interests, :foreign_key => :user_id
accepts_nested_attributes_for :user_interests
interest.rb
has_many :user_interests, :dependent => :destroy
has_many :users, :through => :user_interests, :foreign_key => :interest_id, :dependent => :destroy
user_interest.rb
belongs_to :user
belongs_to :interest
View code:
app/views/user/_form.html.erb
<%= form_for(@user) do |form| %>
... user fields
<%= form.fields_for :user_interests do |ui_form| %>
... loop through ALL interests
<% Interest.all.each do |interest| %>
<%= ui_form.select :rating, options_for_select(1..10) %>
<%= ui_form.hidden_field :interest_id, :value => interest.id %>
<% end %>
<% end %>
<% end %>
I also included the following in new actions / editing in my controller @user.interests.build.build_interest
The problem I am facing is that in the params hash only one percentage rating is passed when I want to have several. I also get an exception thrown by rails
Interest(#2172840620) expected, got Array(#2148226700)
What tiny detail did I miss or am I mistaken that causes the problem?
EDIT:
, HTML - : name user[user_interests_attributes][rating], user[user_interests_attributes][][rating], . : , . , , , , ?
BIG Update:
, , :
:
<% form.fields_for :user_interests do |ui_form| %>
<p>
<%= ui_form.select :rating, options_for_select(1..5), :selected => :rating %>
<%= ui_form.label :interest_title %>
<%= ui_form.hidden_field :interest_id %>
</p>
<% end %>
:
def new
@user = User.new
Interest.all.each { |int| @user.user_interests.build({ :interest_id => int.id }) }
end
def edit
@user = @current_user
Interest.unrated_by_user_id(@user.id).each { |int| @user.user_interests.build({ :interest_id => int.id }) }
end
user_interests, , , , . , , , . - ?