开发者

I can get correct data to display in my ERB, but I'm not following the standards. Can you help?

开发者 https://www.devze.com 2023-02-08 15:15 出处:网络
I have two models: user and transaction. Transactions table has user_id column for storing the id of the user responsible for transaction.

I have two models: user and transaction. Transactions table has user_id column for storing the id of the user responsible for transaction.

On the index.html.erb for transactions this was the auto generated code:

<td><%=h transaction.user_id %></td>

Since I want user's name to be displayed, in my first approach I converted this to:

# Index.html.erb
# First approach
<td><%=h User.find(:first, :conditions => ["id =?", transaction.user_id]).firstname %></td>

This got me the firstname correctly, but I was not sure this was the right way so I created this method in user.rb (model file):

# user.rb
# Second approach
def find_by_id id
    @firstname = User.find(:first, :conditions => ["id =?", id]).firstname开发者_开发百科
    return @firstname
end

And modified the line in index.html.erb to:

# Index.html.erb
# Second approach
<td><%=h User.find_by_id(transaction.user_id) %></td>

But this does not give me user's firstname and instead the output is something like #<User:0x000000021ecf60>

I am not sure: a) Why this is happening and how to get the return from method to print correctly & b) If I am following standards even in second approach to getting the username printed.


Assuming you have your association between transactions and users setup properly in the transaction model:

class Transaction < ActiveRecord::Base
  belongs_to :user
end

Then you can simply do:

<td><%=h transaction.user.firstname %></td>

The reason your 'find_by_id' method didn't work is because you created it as an instance method. So, when you called User.find_by_id, it used the normal Rails 'magic method' (not so magic at all - it just uses method_missing) for finding records. I would argue that it is very bad design to override this method to just return the first name of the user when you've got all this object-oriented loveliness around.


Yes, you probably forgot to insert belongs_to association to transaction.rb model.

Be sure that table transaction has a field user_id.

More on this here: http://guides.rubyonrails.org/association_basics.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号