阅读重大更新以获取最新信息。
嘿大家,
我在一个涉及三个表的 Rails 应用程序中有一个多对多关系:一个用户表、一个兴趣表和一个连接 user_interests 表,该表也有一个评分值,因此用户可以对他们的每个兴趣进行评分1-10 级。
我基本上是在寻找一种方法,让新用户在注册时创建他们的评级,并在未来日期同时编辑他们的任何个人资料信息。
我试图通过 has_many 来关注这个问题 Rails nested form :through, how to edit attributes of join model? 但我遇到的问题是尝试将选择列表合并到组合中,并为用户评分多个兴趣。
型号代码:
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
查看代码:
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 %>
我还在控制器的新/编辑操作中包含以下内容@user.interests.build.build_interest
我遇到的问题是,当我想要多个时,参数哈希中只传递了一个利率等级。我也得到了rails抛出的异常
Interest(#2172840620) expected, got Array(#2148226700)
我遗漏了哪些微小的细节或弄错了导致问题的原因?
编辑:
我找到了一种强制它工作的方法,但它需要在 chrome 开发人员工具中手动编辑 HTML,我的表单元素的 :name 属性正在生成,user[user_interests_attributes][rating]
但如果我将其更改为user[user_interests_attributes][][rating]
它将在我更新记录时工作。但是,我无法手动指定绑定到表单对象的表单元素的 :name。那么我能做些什么来证明正在通过多个利率评级,而不是 Rails 认为的一个?
大更新:
我得到了一个半功能版本,有一些细微的变化:
查看代码:
<% 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,但是当我尝试创建新用户时,我收到一个错误,即用户为空。此外,我无法访问表单中的任何兴趣属性来显示用户实际评分的兴趣。任何人都可以帮助解决这些警告吗?