【问题标题】:I wanna use model attribute in view Rails我想在视图 Rails 中使用模型属性
【发布时间】:2016-04-03 16:48:01
【问题描述】:

我正在尝试在模型中使用属性值,但它不起作用.. 我有三个模型:

models/resident.rb

class Resident < ActiveRecord::Base
  belongs_to :hostel
  has_one :user,dependent: :delete
end

models/user.rb

class User < ActiveRecord::Base
 belongs_to:resident
end

models/hostel.rb

class Hostel < ActiveRecord::Base
  has_many :residents
  has_one :rate_card,dependent: :delete
end

架构

居民

create_table "residents", force: :cascade do |t|
    t.string   "room_number"
    t.string   "roll_number"
    t.string   "name"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "hostel_id"
  end

用户

create_table "users", force: :cascade do |t|
    t.string   "roll_number"
    t.string   "email"
    t.datetime "created_at",                        null: false
    t.datetime "updated_at",                        null: false
    t.integer  "resident_id"
  end

旅馆

create_table "hostels", force: :cascade do |t|
    t.string   "hostel"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

现在我想在 users/show.html.erb 中使用 hostel 属性值 我能够做到这一点:

<%if @user.resident.roll_number=="101303110"%>

如果存在卷号,则返回 true.. 但如果是使用:

<%if @user.resident.hostel=="J"%>

如果 J 是 Hostel 模型中存在的旅馆,则返回 false

但是当我们将&lt;%@user.resident.hostel%&gt; 放入 show.html.erb 时,它会显示 J 值。 我应该如何在其他视图中使用相关模型属性?

【问题讨论】:

  • “想要”? “一世”?如果您查看其他问题和答案,您会发现故意拼写和语法错误的情况相对较少。请保存它以发短信。
  • -_- 我来这里是为了编码帮助,不是为了学习英语!

标签: ruby-on-rails ruby activerecord activemodel rails-models


【解决方案1】:

鉴于您的关联,@user.resident.hostel 将加载一个旅馆。但是您想比较hostel 上的hostel 字符串。因此,您的比较应该是:

<% if @user.resident.hostel.hostel == 'J' %>

解释:

@user                         # returns your a user

@user.resident                # follows `belongs_to :resident` and 
                              # returns a resident

@user.resident.hostel         # follows `belongs_to :hostel` on the resident and
                              # returns a hostel

@user.resident.hostel.hostel  # returns the value store in the `hostel`
                              # column of that `hostel`

顺便说一句。我认为这样的链接调用违反了Law of Demeter。但是如果不深入了解您的应用,就很难提出任何替代方案。

【讨论】:

  • 你能解释一下它的工作原理吗?是的,它正在工作:D
猜你喜欢
  • 2013-12-05
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 2017-07-10
  • 2012-06-09
相关资源
最近更新 更多