简体   繁体   English

简单形式的宝石-如何在关联中显示模型的名称-Rails 4

[英]Simple Form Gem - How to display the name of a model in an association - Rails 4

I'm new to rails & I know this may be a very simple question, but I'm unsure how to display the name of a company using 'simple form' association? 我是Rails的新手,我知道这可能是一个非常简单的问题,但是我不确定如何使用“简单表单”关联显示公司名称?

  • In my schema I've a table companies with the columns name & content 在我的模式中,我有一个表格companies ,其namecontent
  • In my schema I also have a table users with the columns first name , last name & company_id:integer 在我的架构中,我还有一个表users ,其表中的first namelast namecompany_id:integer
  • A company has_many :users company has_many :users
  • A user belongs_to :company user belongs_to :company

Everything works perfectly in my views expect the display of the name of my company 我认为一切正常,希望显示公司名称

in my views: 在我看来:

<h2>Sign up Primary Admin</h2>

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.association :company, collection: Company.all.order(:name), prompt: "please select your company", label: 'Company' %>
    <%= f.input :firstname, required: true, autofocus: true %>
    <%= f.input :lastname, required: true, autofocus: true %>
    <%= f.input :email, required: true, autofocus: true %>
    <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %>
    <%= f.input :password_confirmation, required: true %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Sign up" %>
  </div>
<% end %>

<%= render "users/shared/links" %>

i get the below display: 我得到以下显示: 在此处输入图片说明

label_method => the label method to be applied to the collection to retrieve the label (use this instead of the text_method option in collection_select) label_method =>要应用于集合以检索标签的label方法(使用此方法代替collection_select中的text_method选项)

You should define the label_method to name to display the company names. 您应该定义label_methodname以显示公司名称。

<%= f.association :company, collection: Company.all.order(:name), prompt: "please select your company", label_method: :name, label: 'Company' %>

SimpleForm uses to_s method for association labels, so you have to define your own to_s method for your company model. SimpleForm对关联标签使用to_s方法,因此您必须为company模型定义自己的to_s方法。 i. 一世。 e: e:

class Company < ActiveRecord::Base
  def to_s
    name
  end 
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM