2016-04-28 2 views
0

Я использую драгоценный камень rails-money в первый раз для приложения событий, которое я создаю. У меня есть модель событий, у которой есть столбец «цена» с типом целого числа. Я хочу, чтобы пользователь имел возможность вводить любые вариации, которые они хотят (в пределах разумного), для стоимости события - например, 15,99, 15,99 и т. Д., Но результат вывода должен выглядеть аккуратным и подходящим (15,99 фунта стерлингов). В настоящее время мое поле ввода позволяет мне указать десятичную точку на форме, но она не распознает это на странице показа (15,99 фунта стерлингов, как показано на рисунке 15). Кроме того, у меня есть поле выбора валюты с 3 основными валютами в качестве вариантов £/€/$, но, какой бы выбор я ни делал на странице показа, он выходит как $, так как в приведенном выше примере 15,99 фунта стерлингов составляет 15 долларов. Как это исправить?Драгоценный камень с денежными рельсами - как переопределить валюту по умолчанию и показать десятичные точки

Это код, у меня есть на данный момент -

Event.rb

class Event < ActiveRecord::Base 

belongs_to :category 
belongs_to :user 
has_many :bookings 


has_attached_file :image, styles: { medium: "300x300>" } 
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ 


monetize :price, with_model_currency: :currency 



end 

money.rb

# encoding : utf-8 

MoneyRails.configure do |config| 

    # To set the default currency 
    # 
    #config.default_currency = :gbp 

    # Set default bank object 
    # 
    # Example: 
    # config.default_bank = EuCentralBank.new 

    # Add exchange rates to current money bank object. 
    # (The conversion rate refers to one direction only) 
    # 
    # Example: 
    # config.add_rate "USD", "CAD", 1.24515 
    # config.add_rate "CAD", "USD", 0.803115 

    # To handle the inclusion of validations for monetized fields 
    # The default value is true 
    # 
    # config.include_validations = true 

    # Default ActiveRecord migration configuration values for columns: 
    # 
    # config.amount_column = { prefix: '',   # column name prefix 
    #       postfix: '_cents', # column name postfix 
    #       column_name: nil,  # full column name  (overrides prefix, postfix and accessor name) 
    #       type: :integer,  # column type 
    #       present: true,  # column will be created 
    #       null: false,   # other options will be treated as column options 
    #       default: 0 
    #      } 
    # 
    #config.currency_column = { prefix: '', 
    #       postfix: '_currency', 
    #       column_name: nil, 
    #      type: :string, 
    #     present: true, 
    #     null: false, 
    #     default: 'GBP' 
    #    } 

    # Register a custom currency 
    # 
    # Example: 
    # config.register_currency = { 
    # :priority   => 1, 
    # :iso_code   => "EU4", 
    # :name    => "Euro with subunit of 4 digits", 
    # :symbol    => "€", 
    # :symbol_first  => true, 
    # :subunit    => "Subcent", 
    # :subunit_to_unit  => 10000, 
    # :thousands_separator => ".", 
    # :decimal_mark  => "," 
    # } 

    config.register_currency = { 
    "priority": 1, 
    "iso_code": "GBP", 
    "name": "British Pound", 
    "symbol": "£", 
    "alternate_symbols": [], 
    "subunit": "Penny", 
    "subunit_to_unit": 100, 
    "symbol_first": true, 
    "html_entity": "&#x00A3;", 
    "decimal_mark": ".", 
    "thousands_separator": ",", 
    "iso_numeric": "826", 
    "smallest_denomination": 1 
    } 

    config.register_currency = { 
    "priority": 2, 
    "iso_code": "USD", 
    "name": "United States Dollar", 
    "symbol": "$", 
    "alternate_symbols": ["US$"], 
    "subunit": "Cent", 
    "subunit_to_unit": 100, 
    "symbol_first": true, 
    "html_entity": "$", 
    "decimal_mark": ".", 
    "thousands_separator": ",", 
    "iso_numeric": "840", 
    "smallest_denomination": 1 
    } 

    config.register_currency = { 
    "priority": 3, 
    "iso_code": "EUR", 
    "name": "Euro", 
    "symbol": "€", 
    "alternate_symbols": [], 
    "subunit": "Cent", 
    "subunit_to_unit": 100, 
    "symbol_first": true, 
    "html_entity": "&#x20AC;", 
    "decimal_mark": ",", 
    "thousands_separator": ".", 
    "iso_numeric": "978", 
    "smallest_denomination": 1 
    } 



    # Set default money format globally. 
    # Default value is nil meaning "ignore this option". 
    # Example: 
    # 
    # config.default_format = { 
    # :no_cents_if_whole => nil, 
    # :symbol => nil, 
    # :sign_before_symbol => nil 
    # } 

    # Set default raise_error_on_money_parsing option 
    # It will be raise error if assigned different currency 
    # The default value is false 
    # 
    # Example: 
    # config.raise_error_on_money_parsing = false 
end 

_form.html.erb

<%= f.collection_select :category_id, Category.all, :id, :name, {prompt: "Choose a category"} %> 
<!-- The above code loop assigns a category_id to each event --> 

<%= f.input :image, as: :file, label: 'Image' %> 
<%= f.input :title, label: 'Event Title' %> 
<label>Location</label><%= f.text_field :location, id: 'geocomplete' %></br> 
<label>Date</label><%= f.text_field :date, label: 'Date', id: 'datepicker' %> 
<%= f.input :time, label: 'Time' %> 
<%= f.input :description, label: 'Description' %> 
<label>Number of spaces available</label><%= f.text_field :number_of_spaces, label: 'Number of spaces' %> 
<%= f.input :is_free, label: 'Tick box if Event is free of charge' %> 
<%= f.input :currency, :collection => [['£GBP - British Pounds',1],['$USD - US Dollars',2],['€EUR - Euros',3]] %> 
<%= f.input :price, label: 'Cost per person (leave blank if free of charge)' %> 
<%= f.input :organised_by, label: 'Organised by' %> 
<%= f.input :url, label: "Link to Organiser site" %> 

<%= f.button :submit, label: 'Submit' %> 

<% end %> 

show.html.erb

<%= image_tag @event.image.url %> 

<h1><%= @event.title %></h1> 
<p>Location </p> 
<p><%= @event.location %></p> 
<p>Date</p> 
<p><%= @event.date.strftime('%A, %d %b %Y') %></p> 
<p>Time</p> 
<p><%= @event.time.strftime('%l:%M %p') %></p> 
<!-- above expresses date and time as per UK expectations --> 
<p>More details</p> 
<p><%= @event.description %></p> 
<p>Number of Spaces available</p> 
<p><%= @event.number_of_spaces %></p> 
<% if @event.is_free? %> 
    <p>This is a free event</p> 
<% else %> 
<p>Cost per person</p> 
<p><%= humanized_money_with_symbol @event.price %></p> 
<% end %> 
<p>Organiser</p> 
<p><%= @event.organised_by %></p> 
<p>Organiser Profile</p> 
<button><%= link_to "Profile", user_path(@event.user) %></button> 
<p>Link to Organiser site</p> 
<button><%= link_to "Organiser site", @event.url %></button> 

<p>Submitted by</p> 
<p><%= @event.user.name %></p> 


<% if user_signed_in? and current_user == @event.user %> 
<%= link_to "Edit", edit_event_path %> 
<%= link_to "Delete", event_path, method: :delete, data: { confirm: "Are you sure?"} %> 
<%= link_to "Back", root_path %> 
<% else %> 
<%= link_to "Back", root_path %> 
<%= link_to "Book the Event", new_event_booking_path(@event) %> 
<% end %> 

Резервные деньги ReadMe заявляют, что деньги на обработку денег - в этом случае «цена» могут быть «монетизированы с помощью миграции». Является ли это обязательным до того, как помощники драгоценных камней будут работать?

ответ

0

Я считаю, что денежный камень позволяет переопределить значение по умолчанию в модели. Поскольку вы хотите иметь возможность выбирать валюту, этот драгоценный камень может оказаться непригодным для ваших целей. Похоже, вам нужно будет добавить валютный метод для своей модели, чтобы пользователь мог выбрать валюту события. Это должна быть простая миграция.

+0

Привет, У меня есть варианты валюты отсортированы, и пользователь может выбрать один из трех, но на странице показа его возврат к умолчанию ($). –

Смежные вопросы