Ruby on rails 在具有外键的表中插入记录-RubyonRails

Ruby on rails 在具有外键的表中插入记录-RubyonRails,ruby-on-rails,foreign-keys,form-for,Ruby On Rails,Foreign Keys,Form For,怎么做呢?我是Rails的初学者。我可以给你一个想法 1.首先更新您的关联。 2.使用用户首选项实现表单,并使用嵌套表单。 您的用户首选项类应如下所示: def create @pref = preference.new(params[:pref]) redirect_to @pref end 以您的形式: 在构建新操作时,使用两个单独关联的字段 如果我正在解决这个问题,我会这样设计我的表单。 好处: 1.可维护代码 2.控制器中的代码更少 3.在

怎么做呢?我是Rails的初学者。

我可以给你一个想法
1.首先更新您的关联。
2.使用用户首选项实现表单,并使用嵌套表单。

您的用户首选项类应如下所示:

 def create
        @pref = preference.new(params[:pref])
        redirect_to @pref
      end
以您的形式:

在构建新操作时,使用两个单独关联的字段

如果我正在解决这个问题,我会这样设计我的表单。 好处:
1.可维护代码
2.控制器中的代码更少
3.在单位职责上更加灵活。

尽管考虑了语法错误,但您可以遵循此模式

  %= form_for @user_preference, url: {action: "create"} do |f| %>
    <%= select_tag(:user_id, options_for_select(@user_options)) %>

<p><p> Preference 1 : 
<%= select_tag(:days_id, options_for_select(@day_options)) %>
<%= select_tag(:location_id, options_for_select(@building_options)) %>
<%= select_tag(:time_id, options_for_select(@time_slot_options)) %>
</p>
<p> Preference 2 : 
<%= select_tag(:days_id, options_for_select(@day_options)) %>
<%= select_tag(:location_id, options_for_select(@location_id)) %>
<%= select_tag(:time_pref_id, options_for_select(@time_pref_id)) %>
</p>

<%= f.submit "Submit" %>
 def create
        @pref = preference.new(params[:pref])
        redirect_to @pref
      end
class UserPreference < ActiveRecord::Base
    belongs_to :user_job
    has_one :preference_one, :foreign_key => 'prefer1_id', :dependent => :destroy, :class_name => "UserPreference"
   has_one :preference_two, :foreign_key => 'prefer2_id', :dependent => :destroy, :class_name => "UserPreference"

  accepts_nested_attributes_for :preference_one # configure your options
  accepts_nested_attributes_for :preference_two # configure your options
end


class Preference < ActiveRecord::Base
    # ...
    belongs_to :user_preference, :foreign_key => 'prefer1_id', :dependent => :destroy, :class_name => "UserPreference"
    belongs_to :other_user_preference, :foreign_key => 'prefer2_id', :dependent => :destroy, :class_name => "UserPreference"
end
def new
   @user_preference = UserPreference.new
   @user_preference.build_preference_one
   @user_preference.build_preference_two
end

def create
    @user_preference = UserPreference.new(user_preference_params)
    # make sure you add your nested attributes on the permitted param list.
end