2

Guys I'm new to RoR and MVC.

I've a model which deals with loan beneficiary's data. To access the structured data (including small piece of HTML data) I created a method like this

class Beneficiary  < ActiveRecord::Base
  def  info
     "#{name}</br>#{age},#{sex}</br><b>Address :</b>#{address}"
  end
end

And in the view, I'm using this info something like this

<%= @b.info.html_safe %>

were, b is an instance of Beneficiary class

It's working fine for me. I just want to know that, Am i violating the MVC rule here? Is it valid to include view code in Model?

4

3 回答 3

3

If you want to use HTML tag to display data you can write helper method instead of writing into model.Or more you want to re factor or clean your code you can watch draper or presenter

于 2012-04-09T05:21:45.500 回答
2

It's better to put this into a helper file.

# /app/helpers/beneficiary_helper.rb

module BeneficiaryHelper

  def beneficiary_info(b)
    "#{b.name}<br>#{b.age},#{b.sex}<br><b>Address:</b>#{b.address}"
  end
end

In your view, you can simply use

<%= raw beneficiary_info(@b) %>

Note: I'd recommend using <span> elements with a class attribute and CSS to handle line breaks and font weights instead of <br> and <b>

Additional Note: If you want helper to be available for the entire application, you can put it in /app/helpers/application_helper.rb

于 2012-04-09T05:23:27.147 回答
0

I'm sure a model it's not the place where to put HTML, use an helper is an improvement for sure but consider the possibility to use a partial:

# /views/beneficiaries/_beneficiary.html.erb
<%= beneficiary.name %><br />
<%= beneficiary.age %>,<%= beneficiary.sex %><br />
<b>Address :</b><%= beneficiary.address %>

and then in your view when you need to show the beneficiary info render this partial:

<%= render @beneficiary %>

UPDATE: If you need to show the beneficiary in a way and his/her info in a different way you should put beneficiary info in /views/beneficiaries/_info.html.erb and then call render this way:

render :partial => "beneficiaries/info", :locals => {beneficiary: @beneficiary}
于 2012-04-09T11:02:22.913 回答