Ruby On Rails Collection选择

时间:2017-12-14 02:53:36

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

您好我一直关注此文档

https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

并且仍然没有运气使其在我的应用上运行

我一直在接收

错误的参数数量(给定7,预期4..6)

模型

class Student < ApplicationRecord
  belongs_to :school_degree

end



class SchoolDegree < ApplicationRecord
   belongs_to :school
   belongs_to :degree
   belongs_to :college
   has_many :students

    def self.test 
              "#{degree.name} - #{college.name}"

    end    


end

查看

<%= f.collection_select(:student , :school_degree , SchoolDegree.all, :id, :test, {prompt: 'College Degree'},{class: "form-control"}) %>

4 个答案:

答案 0 :(得分:4)

试试这个:

将您的类方法更改为实例方法

class SchoolDegree < ApplicationRecord
   belongs_to :school
   belongs_to :degree
   belongs_to :college
   has_many :students

    def test 
       "#{degree.name} - #{college.name}"
    end    


end

在视图中;

<%= f.collection_select(:school_degree_id , SchoolDegree.all, :id, :test, {prompt: 'College Degree'},{class: "form-control"}) %>

答案 1 :(得分:1)

你不应该需要:学生

a <- c(1, 2, 3)
b <- c(4, 5)

我看到你正在尝试使用类方法,而文档中的示例却没有。这有什么理由吗?尝试删除自己,如下面

  <%= f.collection_select(:school_degree , SchoolDegree.all, :id, :test, {prompt: 'College Degree'},{class: "form-control"}) %>

答案 2 :(得分:1)

试试这个

class Student < ApplicationRecord
  belongs_to :school_degree

    def test 
          "#{school_degree.degree.name} - #{school_degree.college.name}"

    end
 end

答案 3 :(得分:0)

请尝试以下

<%= f.collection_select :score_id, SchoolDegree.all, :id, :test, { :prompt => 'College Degree'},{ :class => "form-control" } %>

SchoolDegree 模型

def test 
  "#{degree.name} - #{college.name}"
end

了解更多信息,请点击以下链接

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select