Thursday, June 16, 2016

Display Last Child in React Iteration | Fixed issues

Display Last Child in React Iteration | Fixed issues


Display Last Child in React Iteration

Posted: 16 Jun 2016 07:55 AM PDT

I'm trying to implement a message app, without ActionCable for now. When I map over all messages, I want to show only the last message from that user: instead of showing all messages, from a user, I only show the last. I do not know how to achieve that. I thought I could set the key to the user_id instead of the id.

_messagesRender: function(){    var messages = this.props.message.map( function(m, i){      return(        <li key={m.user_id}>{m.body}</li>      )    });    return(      <div>{messages.length === 0 ? "No messages" : messages}</div>    )  },  

This component is on the index page and I'm trying to create a message-like app. Any pointers with React? Rails 5 is used as back end.

Warning: flattenChildren(...): Encountered two children with the same key, .$2. Child keys must be unique; when two children share a key, only the first child will be used.

Back end:

@messages = Message.where(to: current_user.id)  

Message model: :id, :to, :user_id, :body

user_id is who sends/created the message.

Any good pattern library creator thats compatible with rails/reactjs?

Posted: 16 Jun 2016 07:57 AM PDT

Could anyone recommend a good UI component library generator that would work well with rails for showcasing css and react ui components?

I've been trying to get https://github.com/kadirahq/react-storybook to work with my current rails/react project, but ultimately couldn't share compiled css files from my rails asset pipeline with the server used in react storybook.

NoMethodError: undefined method `in_time_zone' for nil:NilClass

Posted: 16 Jun 2016 07:26 AM PDT

I am trying to insert data into my TimeSlot table. Overtime I run the code, I get this error "NoMethodError: undefined method `in_time_zone' for nil:NilClass"

Here is the code for inserting data:

 starts_at= begin_date   time_slot=TimeSlot.create( starts_at: '',                                    length: 15,                                    provider_id: '',                                    practice_location_id: '',                                    practice_id: '',                                    day_of_the_week: ' ',                                    timezone: "Central Time (US & Canada)",                                    hour_of_the_day: 1,                                    health_post_id: time_slot_start_health_post_id,                                    deleted_at: 'NULL',                                     health_post_url: url,                                    cached_reason_for_visits_list: "8~Allergic Asthma|9~Allergic Cough|10~Allergic Eye Problems|7~Allergy Consultation|5~Discharge (ER) Follow Up Visit|6~Discharge (Hospital) Follow Up Visit|11~Drug Allergy|12~Eczema|3~Follow Up – Established Patient|13~Food Intolerance|2~General Consultation|14~Hay Fever|15~Hives|1~New Patient|16~Poison Ivy|4~Sick Visit – Established Patient|17~Skin Rashes",                                    type_of_patient: "any_test")  

Here is the function for time_zone in the model

   def local_starts_at       set_timezone unless self.timezone         @local_starts_at ||= self.starts_at.in_time_zone(self.timezone)     end  

Please help.

Rails 4.2: After manual changing of model name Rails server complains about helpers for the old model

Posted: 16 Jun 2016 07:10 AM PDT

I'm working on Rails4.2/mongoid application.

I needed to change the name for one model and did it manually. I'm confident that there is no mention of the old model name in any of the files, checked over and over again manually and then with grep. Also changed the collection name in MongoDB

Attempt to open any url on the application results in

Couldn't find ExamplesHelper, expected it to be defined in helpers/examples_helper.rb

Application trace point's to

app/controllers/application_controller.rb:1:in '<top (required)>' app/controllers/home_controller.rb:1:in '<top (required)>'

There is no mention of any models/controllers/helpers in the above controllers. These are the only two inheriting from ActionController::Base

I found a similar question, but can't say I like the solution.

Can anybody at least point me in the right direction? Really stumped with this one.

Rails engine: NameError: uninitialized constant Active****. Using require 'active_***' acceptable?

Posted: 16 Jun 2016 07:19 AM PDT

I'm working with a rails engine which uses ActiveRecord/ActiveJob and getting an error:

NameError: uninitialized constant ActiveJob  

To fix this, within the engine.rb I added a require e.g.

require 'active_job'    module MyMod    class Engine < ::Rails::Engine    ...  

However it has been suggested to me that this is a bad way to solve the problem and that an alternative is to check that the Constant is defined instead within the affected method call. e.g. if defined?(ActiveJob). I am less happy with that solution.

Can anyone suggest any resources that discuss this, suggest why 'require' may be bad, or suggest alternate solutions?

EDIT: I should state that both solutions actually fix the problem; its as much a matter of understanding why within a Rails engine the Rails classes (e.g. ActiveRecord/ActiveJob) are not available unless explicitly required (which I suspect is simply that an engines dependencies are not autoloaded) and how 'best' to make them available within the engine itself.

MD5 for entire asset pipeline?

Posted: 16 Jun 2016 06:59 AM PDT

Is there any sort of MD5 hash or cache key generated by the asset-pipeline that represents all the files in the assets folder? I'm looking for a way to know when assets have been added, removed, or updated between deploys.

Rails Postgres hstore or jsonb to store many to many relations

Posted: 16 Jun 2016 07:42 AM PDT

There is a table 'Products' with columns (id, tile, price, description, shop_id, timestamps) Column price and shop_id are dynamic. The rest of column are static.

Also there is a table 'Shops' with columns (id, name, timestamps).

Shop has many products. Product can migrate among all shops and products.shop_id can be blank.

I want to have history about which products a shop had. For example, yesterday shop had products and their prices. Day before yesterday shop had other products and/or other their prices. So I want to have something like

'ShopHistory' (id, data, date, timestamps), where data is hstore or json. So it should have hash like { key: value}, where key is id of product and value is its current price. But I would like to joins data column with products in order to know about title and description of products. I have no idea how to do that. It looks like ShopHistory is a join table between shop and products, but all information are stored in one row.

Could we help me? Maybe anyone knows a better way to implement all of this. Any thought and articles are welcome.

Thanks!

P.S. I use rails(ActiveRecord) and PostgreSQL, but answers from guys who know only Postgres are good for me too.

Uninitialized constant Mysql

Posted: 16 Jun 2016 07:20 AM PDT

I'm working on a web service to access my database via mysql, but I keep getting this error : NameError - uninitialized constant Mysql

When I created the Database, i did not add a password to it. I am using Microsoft SQL Management Studio. To test the web service i am using Advanced REST client.

This is my code

get '/all_users/' do  conn=Mysql.new('localhost','My-PC\Nikki','', 'My-PC\Project')  recordsArray = "{\"clientList\":["  clientArray = Array.new  sql = 'select * from ServerUsers'  records = conn.do(sql) do |record|      client = AndroidtableClientsSearch.new(record[0],record[1],record[2],record[3], record[4])      clientArray<<client.to_s  end  conn.logoff  recordsArray<<clientArray.join(',')  recordsArray<<"]}"  recordsArray  end  

Update table from database using ajax in rails

Posted: 16 Jun 2016 07:07 AM PDT

I have a problem. I want update my table data from database with selected value's for select box (dropdown). And i think ajax is solution. But how can i do it?
Here is my select tag in VIEW. My view is writtin in haml

%select{:name => "options", :id=>"select_other_month"}              %option{:value => "0"} Other Months              %option{:value => "5"} 5              %option{:value => "4"} 4              %option{:value => "3"} 3              %option{:value => "2"} 2              %option{:value => "1"} 1   

and here is my table

.table{:id=>"admin_time_table"}          %table{:border=>"1"}              %tr                  %th No                  %th Name                  %th Total day                   %th Total time              -@i = 1              -@users.each do |u|                  %tr                      %td=@i                      %td=u.firstname                      %td=u.total_day                      %td=u.total_time                  -@i = @i +1  

and my controller looks like

@users = User.where(:type_id=>0)  

I mean when i select 4 in dropdown, table data reloaded with April data from database.
Note: My database is mysql.
Sorry for my bad English.

Trying to send email with gmail stp (rails)

Posted: 16 Jun 2016 06:51 AM PDT

I'm trying to send some emails from my web application. Here is my configuration :

//config/environments/development.rb  config.action_mailer.delivery_method = :smtp  config.action_mailer.smtp_settings = {  address:              'smtp.gmail.com',  port:                 587,  domain:               'domain.com',  user_name:            'myusername',  password:             'mypassword',  authentication:       'plain',  enable_starttls_auto: true  }   

.

// mailers/contact_mailer  class ContactMailer < ApplicationMailer  default from: 'from@gmail.com'    def send_email()      mail(to: 'to@gmail.com', subject: 'Welcome to My Awesome Site')  end  end   

.

// views/contact_mailer/send_email.html.erb  <!DOCTYPE html>  <html>  <head>  <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />  </head>  <body>  <h1>Welcome to example.com, name</h1>  <p>  <p>Thanks for joining and have a great day!</p>  </body>  </html>   

.

so to test it, i runned this commande from the rails command: ContactMailer.send_email

and i'm getting this result :

irb(main):003:0> ContactMailer.send_email  Rendered contact_mailer/send_email.html.erb within layouts/mailer (0.1ms)    ContactMailer#send_email: processed outbound mail in 10.4ms  => #<Mail::Message:69980432504260, Multipart: false, Headers: <From:    adib.elaraki@gmail.com>, <To: adib.amine.mdr@gmail.com>, <Subject: Welcome   to My Awesome Site>, <Mime-Version: 1.0>, <Content-Type: text/html>>  irb(main):004:0>   

Unfortunatly, after checking my email, i don't receive the email :(

Rails 4: some of params missing on form_tag after submitting

Posted: 16 Jun 2016 06:13 AM PDT

In our Rails 4 app, there is a form_tag on misc definitions index form for CSV download. Here is the form_tag looks like:

<%= form_tag misc_definitions_path(format: "csv", subaction: 'role_definition'), method: :get do %>             <div class="form-inputs">                <%= label_tag(:index_from, "Index From") %>                <%= text_field_tag('index_from', '1', size: 6) %>                <%= label_tag(:token, "Token ") %>                <%= text_field_tag('token?', '', size: 12) %>                <%= hidden_field_tag 'project_id', @project.id %>                <%= hidden_field_tag 'definition_category', 'role_definition' if @definition_category == 'role_definition' %>                <%= hidden_field_tag 'definition_category', 'position_definition' if @definition_category == 'position_definition' %>               <%= submit_tag 'CSV' %>             </div>        <% end if @project && (@definition_category == 'role_definition' || @definition_category == 'position_definition') %>  

When the misc_definitions index page is initially loaded, the params has the value when debug in one method:

enter image description here

After clicking CSV to start download, the params becomes:

enter image description here

Obviously all hidden_field_tag and format & subaction passed in misc_definitions_path are all missing. Why those params mentioned above are missing in 'submit (for CSV download)?

Import data from csv file to postgresql database in rails

Posted: 16 Jun 2016 06:08 AM PDT

I have tried the following for importing data from csv file in rails but couldn't understand where I have to use the particular code and how to save particular db column with specific columns of CSV.

require 'csv'      csv_text = File.read('...')  csv = CSV.parse(csv_text, :headers => true)  csv.each do |row|  User.create!(row.to_hash)  end  

And where should we keep the csv file to be imported. Can we give path like /Downloads/users.csv in File.read()? And what if the field in csv file is referenced by another table and can we use like the following:

require 'csv'      csv_text = File.read('...')  csv = CSV.parse(csv_text, :headers => true)  csv.each do |row|  Project.new  Project.client = project.where(:client_code, row.client_code)  

Can we use something like this?

I have referred the following link but couldn't understand completely. Ruby on Rails - Import Data from a CSV file

Loop through rails associations

Posted: 16 Jun 2016 06:19 AM PDT

1)I'm trying to create a site that has several restaurants each having their own unique menu being displayed in a table, the association works in the console but not in code.I loop over the @restaurant instance variable then in the table I put the data I want from the menu so restaurant.menu.dish but getting an error that 'each' is undefined even though I didn't state a one-one relationship.How may I carry out the desired behavior?

2) How do I ensure that the menu data corresponds with the right restaurant,I'm assuming that the show controller saves the restaurant variable with a specific ID and calling a method like .dish would know what restaurant based on the show action variable, is this correct thinking?

Restaurant Model

class Restaurant < ActiveRecord::Base      has_attached_file :thumbnail, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"    validates_attachment_content_type :thumbnail, content_type: /\Aimage\/.*\Z/    has_many :menus      def self.search(search)      if search      @restaurants= Restaurant.where("name LIKE ?", "%#{search}%")      else        @restaurants=Restaurant.all      end      end  end  

Menu Model

class Menu < ActiveRecord::Base    belongs_to :restaurant  end  

Restaurant controller with show action

def show    @restaurant = Restaurant.find(params[:id])  end  

Show.html.erb

<div class="col-md-8">    <table class="table table-striped">      <h3>Menu</h3>      <thead><tr><th>Dish</th><th>Price</th><th>Calories</th></tr></thead>      <tbody>      <%= @restaurant.each do |restaurant| %>          <tr>              <td><%= restaurant.menu.dish %></td>              <td><%= restaurant.menu.price %></td>              <td><%= restaurant.menu.price %></td>          </tr>          <tr><td>..</td><td>..</td><td>..</td></tr>      <% end %>      </tbody>    </table>  </div>  

Error While installing rails, i18n requires Ruby version >= 1.9.3 [duplicate]

Posted: 16 Jun 2016 07:48 AM PDT

This question already has an answer here:

I am working on a project that requires Ruby 1.8.7 and Rails 3.1.1.

I used RVM to install Ruby and it was installed fine. But, when I try to install Rails,

$ gem install rails --version '3.1.1'  

It is throwing an error:

ERROR:  Error installing rails:      i18n requires Ruby version >= 1.9.3.  

Can someone please help?

Push parallelization stop randomly on heroku

Posted: 16 Jun 2016 07:36 AM PDT

I want to send a push campaign to all my users (around 500k), but the heroku dyno stop randomly during the execution (no exception raised). I am using the gem Parallel :

User.where(some_stuff).find_in_batches(batch_size: 1000) do |group|    Parallel.each(group, in_threads: 8) do |u|      u.push('hi') # pushing the message via GCM or APN    end  end  

In all the cases I tested, the process stops at the end of a batch, but I can't find a pattern when playing with batch_size and in_threads values.

The push function doesn't need a database access, but maybe that the find_in_batch function get rejected because of too many connections?

I use a performance-l dyno with 14GB RAM

Amazon - pictures are disappearing

Posted: 16 Jun 2016 05:55 AM PDT

I have an app, that use Amazon S3 as a picture storage. My is: Ruby on Rails + MongoDb + Carriervawe + Fog + VDS.

Sometimes pictures, that belongs to some model class, just disappear from Amazon.

E.g., I have model Gallery has_many :photos. Sometimes all photos within 1 gallery lost all pictures.

Meanwhile, all links to S3 (that are generated by carriervawe and fog) are present!

It happens with different models and there instances. And it happens rarely - maybe once per month/2 months.

My ideas are:

  • Amazon errors
  • Some faulty requests from mongo/fog/carriervawe, that I do not initiate.

Any ideas?

Thank you for your help!

When setting up a new rails app with devise and activeadmin the schema.rb ends up empty

Posted: 16 Jun 2016 06:02 AM PDT

I have now set up around 3-4 rails apps using Rails Composer:

  1. I create the Rails app using rails composer using a MySQL database
  2. I setup active admin

Then at some point during the setup running bin/rake db:migrate completely clears my schema.rb and the users table is removed.

I always have to restart my computer and run bin/rake db:migrate again and my schema.rb is then fixed.

I have no idea why this problem occurs but I think it's related to devise and active admin (which in turn uses devise as well).

The problem only occurs during the setup and I usually don't have that problem again.

The schema.rb when this happens:

ActiveRecord::Schema.define(version: 0) do    end  

Why does this occur?

Mass assign error

Posted: 16 Jun 2016 07:43 AM PDT

Rails 3.2  

In my form, I have the following (using slim):

= form_for CustomerInfo.new :url => {:action => "create"}, :method => "post" do |f|  ....  ....  .actions = f.submit 'Save'  

This is generating the following error:

Can't mass-assign protected attributes: url, method  

In my routes.rb, I have:

post '/customer_infos' => 'customer_infos#create', as: 'customer_info'  

Isn't this syntax allowed under Rails 3.2?

Solution:

I solved it by doing:

= form_fo(CustomerInfo.new :url customer_info_path) do |f|  

Adding input with simple_form to get <datalist>

Posted: 16 Jun 2016 06:02 AM PDT

I am trying to use simple_form to generate an input textfield with collections, equal to

<input list="browsers" name="browser">  <datalist id="browsers">  <option value="Internet Explorer">  <option value="Firefox">  <option value="Chrome">  <option value="Opera">  <option value="Safari">  </datalist>  

something to be like: enter image description here

Rails create File with content type text/xml

Posted: 16 Jun 2016 05:38 AM PDT

I create an xml file with:

    xml_device_path = "#{xml_device_description.get_file_path_without_name}#{title}.xml"        File.open("#{xml_device_path}", 'w') do |f|          f.puts(content.to_xml)      end   

to attach this file via paperclip to my model.

file = File.open("#{xml_device_path}")  xml_device_description.xml = file  file.close  

The resulting file has the content type "application/xml" but I need the content type "text/xml".

Is it possible to set or to manipulate the content type of an file or during the file creation?

Thanks a lot.

How do I prevent devise from storing sessions when basic auth is used?

Posted: 16 Jun 2016 05:35 AM PDT

Disclaimer: I am a relatively novice RoR developer.

My rails 4 web app supports a RESTful API. I am using devise, and the API authenticates with basic auth without any use of keys/tokens (so basic auth must be used on each request). It works fine, except for this: If you are logged out and hit the API in the browser it stores a session, so then if you go back to the web app, you are logged in. This is not the behavior I want. The user should be redirected to the sign-in page when they hit the API and then hit the web app (unless they were already logged in to begin with). So how to I prevent devise from storing a session when basic auth is used?

Relevant code: In the application controller I have:

before_action :authenticate_user!  

And in devise.rb I have:

config.http_authenticatable = true  

Checking a table for time overlaps

Posted: 16 Jun 2016 05:20 AM PDT

I have a problem with my custom validation. There is individual_trainings table.

# Table name: individual_trainings  #  #  id               :integer          not null, primary key  #  date_of_training :date             not null  #  client_id        :integer  #  trainer_id       :integer  #  end_on           :time             not null  #  training_cost_id :integer  #  start_on         :time             not null  

I want to create validation method that checks if client has another training on the same day and time start_on, end_on overlaps with another training throw error.

  def client_individual_training_validation      client.individual_trainings_as_client.where('date_of_training = ?', date_of_training).each do |ci|        if (start_on...end_on).overlaps?(ci.start_on...ci.end_on)          errors.add(:error, 'You have a training in the same time.')        end      end    end  

There is a problem with this method, because if new date and time is correct(not overlap), create method passes and add new training in database.but also there is a alert error message, that term is already busy. How to fix it?

How to save the return customer data with stripe

Posted: 16 Jun 2016 05:17 AM PDT

I am using payola which is a rails engine for stripe payment. I am using the subscriptions method to make subscription. Currently users are able to make subscription and can save the data on stripe. How do I save the return data to my database?

param is missing or the value is empty rails controller

Posted: 16 Jun 2016 06:03 AM PDT

I have a 3 views, with create form, but a sample def new def create works good, but other def not works...

RateFormController.rb

class RateFormController < ApplicationController      def new          @rateform = RateForm.new      end        def create        @rateform = RateForm.new(rate_params)        if @rateform.save          redirect_to :root          RateFormMailer.rate_email(@rateform).deliver_now        end      end        def encreate         @rateform = RateForm.new(rate_params)          RateFormMailer.rate_email(@rateform).deliver_now         # ContactsMailer.sample_email(@contact).deliver_now      end        def rucreate         @rateform = RateForm.new(rate_params)         if @rateform.save          redirect_to :root          RateFormMailer.rate_email(@rateform).deliver_now          end      end          private      def rate_params         params.require(:rate_form).permit(:name, :mail, :comment, :ratename, :phone)      end    end  

127.0.0.1:3000/rate_form/encreate

ActionController::ParameterMissing in RateFormController#encreate param is missing or the value is empty: rate_form

Needs refresh in order to display created items

Posted: 16 Jun 2016 07:05 AM PDT

I am working on a simple tool that adds budgets to teams. It works similar to a to do list.

The delete function works without reloading but the create function needs a refresh (the data gets added to database fine).

This is the create.js.erb

$('.budget_items').append("<%= j render partial: 'budget', locals: {budget: @budget} %>");  

This is the partial: _budget.html.erb

<li id="<%= budget.id %>">  <%= budget.budget_item %>  <%= budget.quantity %>  <%= budget.cost_per_item %>  Total cost: <%= budget.quantity * budget.cost_per_item %>  <%= link_to "delete budget item", project_team_budget_path(@project, @team,      budget), method: 'delete', remote: true %>  </li>    <h1>My Estimated Budget</h1>  <h3>Total Budget: </h3>    <%= simple_form_for [@project, @team, @budget], remote: true do |f| %>      <div class="form-group">      <%= f.input :budget_item %>    </div>      <div class="form-group">      <%= f.input :quantity %>    </div>      <div class="form-group">      <%= f.input :cost_per_item %>    </div>      <div class="form-group">    <%= f.submit "Add budget item" %>    </div>  <% end %>    <ul class="budget_items">    <%= render @budgets %>  </ul>  

This is the budget controller:

class BudgetsController < ApplicationController      def index      @budgets = Budget.all    end      def create      @team = Team.find(params[:team_id])      @budget = @team.budgets.create(budget_params)      respond_to do |format|        format.html { redirect_to project_team_budgets_path }        format.js { }      end    end      def destroy      @team = Team.find(params[:team_id])      @budget = @team.budgets.find(params[:id])      @budget.destroy      respond_to do |format|        format.html { redirect_to project_team_budgets_path }        format.js { }      end    end      private      def budget_params      params.require(:budget).permit(:title, :budget_item, :quantity, :cost_per_item)    end  end  

Regarding masking urls in ruby

Posted: 16 Jun 2016 04:44 AM PDT

I am developing an application in ruby on rails , here i want to pass parameters in the URL itself.so my URL looks like "localhost:3000/deals?category_id=1&city_id=1".But i want to just show
"local host:3000/deals".Is there any way to mask the URL in routes?

SEO friendly urls containing / in Rails

Posted: 16 Jun 2016 04:42 AM PDT

I am currently working on transferring pages from a wordpress to a new Rails application to save time on reindexing i would like to keep same url structure

These urls contain /

There for having a page with slug /p/chapter/part/section gives me /p/chapter%2Fpart%2Fsection in the url after rendering

I know module URI is available but i simply dont know how to implement it

what i have dont to achieve Slug style url is

Pages controller

def set_page    @page = Page.find_by_slug(params[:id])  end  

and Pages model

def to_param   "#{slug}"  end   

routes

resources :pages , :path => 'p'  

if anyone could help it would be very much appreciated.

undefined local variable or method `author' for #<AuthorsController:0x94c5ee8>

Posted: 16 Jun 2016 06:56 AM PDT

I am trying to submit information into a PHP database and I am getting this error.

authors_controller.rb

class AuthorsController < ApplicationController    def new      @page_title = 'Add New Author'      @author = Author.new    end      def create      @author = Author.new(author_params)      @author.save        redirect_to authors_path    end      def update    end      def edit    end      def destroy    end      def index    end      def show    end      def author_params       params.require(author).permit(:first_name, :last_name)    end   end  

when I click on submit button the error pops up.

Event layout design ruby [on hold]

Posted: 16 Jun 2016 05:03 AM PDT

I'm creating an web app for selling online tickets.The user will be able to design a seating chart. Each seating chart has a collection of seats. These seats can be assigned unique numbers or names. You can organize seats into larger groups, such as rows, sections, or levels.

So will be something similar to https://www.ticketlight.co.uk/seating-map-editor Will look like this

Rails nested form Unpermitted parameter

Posted: 16 Jun 2016 04:30 AM PDT

When i create or edit product, my merchant_product_detail will not be created or edit due to
Unpermitted parameter: merchant_id. But other like id and price are able to pass strong parameters, only merchant_id could not pass it. Kindly help me why my merchant_id is not permit in this case?

params return in binding.pry mode

"product"=>        {"name"=>"fewrgvers",         "description"=>"",         "product_categories_attributes"=>{"0"=>{"id"=>""}},         "merchant_product_details_attributes"=>          {"0"=>{"merchant_id"=>["2"], "id"=>"", "price"=>"123"}}      "  

product_params return

    Unpermitted parameter: merchant_id      => {"name"=>"fewrgvers",       "description"=>"",       "merchant_product_details_attributes"=>{"0"=>{"id"=>"", "price"=>""}}  

product.rb

has_many :merchant_product_details  accepts_nested_attributes_for :merchant_product_details, reject_if: proc { |attributes| attributes['merchant_id'].blank? }  has_many :merchants, through: :merchant_product_details  

merchant.rb

has_many :merchant_product_details  has_many :products, through: :merchant_product_details  accepts_nested_attributes_for :merchant_product_details  

merchant_product_detail.rb

belongs_to :product  belongs_to :merchant  

product_controller.rb

 def new      @product = Product.new      @product.merchant_product_details.build  end    def create      @product = Product.new(product_params)      respond_to do |format|        if @product.save          format.html { redirect_to root_path, notice: 'Product was successfully created.' }        else          format.html { render :new }        end      end    end  end    def update      respond_to do |format|        if @product.update_attributes(product_params)          format.html { redirect_to root_path, notice: 'Product was successfully updated.' }        else          format.html { render :edit }        end      end  end      params.require(:product).permit(:name, :description,         merchant_product_details_attributes: [:id, :merchant_id, :price]  

_form.html.erb

<%= form_for(@product, :url => path, html: { class: "form-horizontal", role: "form" }) do |f| %>  <%= f.fields_for :merchant_product_details do |builder| %>      <div class="form-group row">        <%= builder.label :merchant_id, class: "col-md-2 control-label" %>        <div class="col-md-8">          <%= builder.select :merchant_id, Merchant.all.collect {|x| [x.name, x.id]}, {include_hidden: false} ,prompt: "Select something", multiple: true, class: "select2" %>          <%= builder.hidden_field :id %><br>                <%= builder.label :price %>          <%= builder.number_field :price %>        </div>  <% end %>  

No comments:

Post a Comment