接收#<profile:0x611b5d8>的未定义方法`mood_id'用于关联的Profile模型Rails 4

时间:2016-04-12 19:08:44

标签: ruby-on-rails ruby-on-rails-4 activerecord simple-form

我在将配置文件模型连接到情绪模型时遇到问题,然后将情绪ID保存到用户的个人资料中。如果你能帮助我解决这个问题,我将不胜感激。

_mood_form.html.erb

<%= simple_form_for(@user, url: current_user, html: {multipart: true}, layout: :horizontal) do |f| %>
    <%= f.simple_fields_for :profile do |n| %>
        <%= n.label :mood_id, 'Select a mood' %>
        <%= n.collection_select :mood_id, Mood.all, :id, :name %>
        <%= f.submit 'Change Mood', class: 'btn btn-info-outline' %>
    <% end %>
<% end %>

profile.rb
belongs_to :mood

mood.rb
has_many :profiles

服务器开发日志

NoMethodError - undefined method `mood_id' for #<Profile:0x611b5d8>:
  activemodel (4.2.3) lib/active_model/attribute_methods.rb:433:in `method_missing'
  ransack (1.7.0) lib/ransack/helpers/form_builder.rb:10:in `value'
  actionview (4.2.3) lib/action_view/helpers/tags/collection_select.rb:16:in `block in render'
  actionview (4.2.3) lib/action_view/helpers/tags/collection_select.rb:16:in `render'
  actionview (4.2.3) lib/action_view/helpers/form_options_helper.rb:202:in `collection_select'
  actionview (4.2.3) lib/action_view/helpers/form_options_helper.rb:789:in `collection_select'
  app/views/users/shared/_mood_form.html.erb:4:in `block (2 levels) in _app_views_users_shared__mood_form_html_erb__906227000_76706760'
  actionview

迁移文件

class CreateMoods < ActiveRecord::Migration
  def change
    create_table :moods do |t|
      t.string :name
      t.string :mood
      t.references :profile, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

1 个答案:

答案 0 :(得分:1)

由于你有belongs_to :mood,你应该将mood_id整数字段添加到profiles数据库表中:

 class AddMoodToProfiles < ActiveRecord::Migration
   def change
     add_column :profiles, :mood_id, :integer
   end
 end