【问题标题】:How make association on Rails 4 and Up?如何在 Rails 4 及以上建立关联?
【发布时间】:2017-07-05 00:17:45
【问题描述】:

在用户新视图上创建关联并创建用户后

Location 没有与用户关联,并在 Console 中显示

irb(main):001:0> Location.last ArgumentError: No association found for 名称“用户”。已经定义了吗?

我是 Rails 4 的新手,我没有使用 attr_accessible,而是将 location_attributes 放在强参数上 看看是否解决,但没有解决。

有人有提示吗?

 def user_params
      params.require(:user).permit(:name, :email,:location_id, :password, :password_confirmation, :slug, 
                                   location_attributes:[:id, :location_id])
    end

用户模型

belongs_to :location

位置模型

  has_many :users

  accepts_nested_attributes_for :user, allow_destroy: true

用户新视图

<%= simple_form_for @user do |f| %>

  <%= f.input :name, label: 'Your Name please', error: 'Name is mandatory' %>
  <%= f.input :email, placeholder: 'user@domain.com' %>
    <%= f.input :password, hint: 'No special characters.' %>

    <%= f.input :password_confirmation, inline_label: 'Yes, remember me' %>



<%= f.simple_fields_for :location do |l| %>

      <%= l.input :country, label: "Country", collection: CountryStateSelect.countries_collection %>
<%= l.input :state, CountryStateSelect.state_options(label: "State / Province", form: f, field_names: { :country => :country, :state => :state } ) %>


      <% end %>
    <%= f.button :submit %>
<% end 

%>

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    在您的位置中定义has_many :users,然后定义accepts_nested_attributes_for :user, allow_destroy: true(:users vs :user),因此它正在寻找与您创建的不同的关联。

    您似乎也在创建一个用户表单,该表单将通过 User 模型尝试创建位置,但您的模型设置为通过位置创建用户(因此您的模型与您的视图不匹配)。

    我相信您想要做的是将模型更改为

    用户控制器

    def user_params
      ...location_attributes:[:id, :country, :state])
    end
    

    用户模型

    belongs_to :location
    
    accepts_nested_attributes_for :location, allow_destroy: true
    

    位置模型

    has_many :users
    

    并且应该工作。 (我已经很多年没有做过嵌套表格了,但是查看你似乎正在使用的Simple Form 的wiki,应该这样做)。如果这不起作用,它至少应该是朝着正确方向迈出的一步。

    【讨论】:

    • 谢谢。差不多好了。你就知道如何将 has_model 模型关联到所属模型创建视图
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    相关资源
    最近更新 更多