[1,2]的未定义方法`name':Array

时间:2017-03-17 06:17:42

标签: ruby-on-rails

我有2个模型YearSubject,我正在尝试显示每个特定年份的主题名称列表,但是当我打开show动作时,我收到此错误。我不知道为什么它返回一个ID数组而不是对象。

show.html.erb

<p id="notice"><%= notice %></p>

<p>   <strong>Name:</strong>   <%= @year.name %> </p>

<p>   <strong>list of subjects:</strong>

    <ul>
      <li><%= @year.subject_ids.name %></li>
    </ul>    </p>

<%= link_to 'Edit', edit_year_path(@year) %> | <%= link_to 'Back', years_path %>

Year.rb

class Year < ApplicationRecord
  has_many  :subjects

end

subject.rb中

class Subject < ApplicationRecord
  belongs_to  :year
end

Years_controller.rb

class YearsController < ApplicationController
  before_action :set_year, only: [:show, :edit, :update, :destroy]

  # GET /years
  # GET /years.json
  def index
    @years = Year.all
  end

  # GET /years/1
  # GET /years/1.json
  def show

  end

  # GET /years/1/edit
  def edit
  end

  # POST /years
  # POST /years.json
  def create
    @year = Year.new(year_params)

    respond_to do |format|
      if @year.save
        format.html { redirect_to @year, notice: 'Year was successfully created.' }
        format.json { render :show, status: :created, location: @year }
      else
        format.html { render :new }
        format.json { render json: @year.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /years/1
  # PATCH/PUT /years/1.json
  def update
    respond_to do |format|
      if @year.update(year_params)
        format.html { redirect_to @year, notice: 'Year was successfully updated.' }
        format.json { render :show, status: :ok, location: @year }
      else
        format.html { render :edit }
        format.json { render json: @year.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /years/1
  # DELETE /years/1.json
  def destroy
    @year.destroy
    respond_to do |format|
      format.html { redirect_to years_url, notice: 'Year was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_year
      @year = Year.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def year_params
      params.require(:year).permit(:name)
    end
end

2 个答案:

答案 0 :(得分:1)

从这一行:

@year.subject_ids.name

您似乎在YearSubject模型之间存在一对多关系。

@year.subject_ids会返回属于id的主题@year数组。这就是你的错误。

您想要展示哪个主题名称?!那是你的逻辑错误。

如果要在列表中显示所有主题名称的列表,请将代码更新为:

<ul>
  <% @year.subjects.each do |subject| %>
    <li><%= subject.name %></li>
  <% end %>
</ul>

答案 1 :(得分:0)

在show.html.erb中尝试以下代码

<p id="notice"><%= notice %></p>

<p><strong>Name:</strong> <%= @year.name %></p>

<p><strong>list of subjects:</strong>    
    <ul>
      <li><%= @year.subjects.map(&:name) %></li>
    </ul>
</p>

<%= link_to 'Edit', edit_year_path(@year) %> | <%= link_to 'Back', years_path %>