我不明白如何从我的View中访问其他表中的数据。
我的模特很少。首先是用户,其次是 UsersPreferences 。所以我有用户的设置页面,代码如下所示:
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
...
<div class="checkbox">
<%= f.check_box :notification_about_new_followers %>
<%= f.label 'Notify via email about new followers' %><br />
</div>
此代码有效(用户有行 notification_about_new_followers ),但我想更改它。我决定更好的方法是保持其他表中的偏好。所以我创建了模型 UsersPreferences ,其 user_id 并标记' notify_about_new_followers '。我试图改写我的观点:
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
...
<div class="checkbox">
<%= f.check_box UsersPreferences.find_by_user_id(@user.id).notify_about_new_followers %>
<%= f.label 'Notify via email about new followers' %><br />
</div>
但是当我访问带有代码的页面时,我得到了这样的错误
undefined method `true' for #<User:0x007f8ac180dee8>
我该如何解决这个错误?
用户模型:
class User < ActiveRecord::Base
attr_accessible :name, ... , :notification_about_new_followers
...
has_one :users_preferences
end
UsersPreferences 模型:
class UsersPreferences < ActiveRecord::Base
belongs_to :user, :class_name => "User"
attr_accessible :notify_about_new_followers
end
答案 0 :(得分:1)
这一行:
<%= f.check_box UsersPreferences.find_by_user_id(@user.id).notify_about_new_followers %>
导致错误。 UsersPreferences.find_by_user_id(@user.id).notify_about_new_followers
为true
,因此该行基本上为:
<%= f.check_box true %>
就像错误所说的那样,UserPreferences模型没有'true'属性。
要解决此问题,您需要先阅读MVC(模型 - 视图 - 控制器)。如果不知道MVC是如何工作的,你将无法继续使用Rails。那里有很多很棒的资源,只有google "Model View Controller for rails"。 Here is a good one。有点傻,但是......如果那不是你的风格,可以试试另一个链接。
了解完毕后,查看导航助手fields_for
,然后您就会找到答案。